﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Core;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.IRepository.OrderFlowManage;
using YunSpace.Repository.OrderFlowManage;
using System.Collections.Generic;
using System.Linq;
using YunSpace.Domain.ViewModel.OrderFlowManage;
using MySql.Data.MySqlClient;
using YunSpace.Data;
using System;
using YunSpace.Domain.ViewModel;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Application.SiteMgr;
using YunSpace.Domain.ViewModel.System;
using YunSpace.Core.Excel;
using System.Data;
using System.Reflection;
using System.Data.Common;
using YunSpace.Domain.Entity.BusinessExportManage;
using YunSpace.Application.SystemManage;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain.IRepository.SiteMgr;
using YunSpace.Domain.ViewModel.WeChat.Site;
using YunSpace.Repository.SiteMgr;
using YunSpace.Domain.Entity.SiteLibraryManage;

#endregion

namespace YunSpace.Application.OrderFlowManage
{
    public class ClientOrderApp
    {
        private Log Log;
        private ClientInfosApp clientInfosApp = new ClientInfosApp();
        private ClientReturnvisitrecordApp clientReturnvisitrecordApp = new ClientReturnvisitrecordApp();

        private IClientsProjectbydemandRepository demandOrderService = new ClientsProjectbydemandRepository();
        private IClientOrderRepository service = new ClientOrderRepository();
        private IClientOrderintentionRepository intentionService = new ClientOrderintentionRepository();
        private IClientOrderrecommendRepository recommendService = new ClientOrderrecommendRepository();
        private IClientOrderintentiondetailRepository intentionDetailService = new ClientOrderintentiondetailRepository();
        private IClientOrderpricetalksRepository priceTalksService = new ClientOrderpricetalksRepository();
        private IClientOrderchangerecordRepository changeRecordService = new ClientOrderchangerecordRepository();
        private IClientOrdertakelookDetailRepository clientOrdertakelookDetailRepository = new ClientOrdertakelookDetailRepository();
        private ISiteOrderTakeLookfeedbackRepository takeLookfeedbackService = new SiteOrderTakeLookfeedbackRepository();
        private IClientOrderPriceDetailRepository priceDetailService = new ClientOrderPriceDetailRepository();
        private IClientOrderimpressRepository impressService = new ClientOrderimpressRepository();
        private IClientOrdersigncontractRepository signContractService = new ClientOrdersigncontractRepository();
        private IClientOrderreserveRepository reserveService = new ClientOrderreserveRepository();
        private IClientOrdertakelookRepository takelookService = new ClientOrdertakelookRepository();

        public ClientOrderApp()
        {
            this.Log = LogFactory.GetLogger("LogFactory");
        }

        public IEnumerable<SelectListItemViewModel> GetAllCitys()
        {
            var data = clientInfosApp.GetAllCitys().Select(p => new SelectListItemViewModel
            {
                Text = p.F_FullName,
                Value = p.F_EnCode
            });

            return data;
        }

        public IEnumerable<AreaModel> GetAllAreas(string parentIds)
        {
            if (!parentIds.IsNullOrEmpty())
            {
                using (var db = new RepositoryBase())
                {
                    string strSql = $@"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName from Sys_Area a where a.F_Layers=3 AND a.F_ParentId IN({ parentIds })";

                    return db.FindList<AreaModel>(strSql);
                }
            }
            return new List<AreaModel>();
        }

        public IEnumerable<AreaModel> GetAllBusinessAreas(string parentIds)
        {
            if (!parentIds.IsNullOrEmpty())
            {
                var tempData = string.Join(",", parentIds.Split(',').Select(p => $"'{ p }'"));
                using (var db = new RepositoryBase())
                {
                    string strSql = $@"select a.F_Id,a.F_ParentId,a.F_EnCode,a.F_FullName from Sys_Area a where a.F_Layers=4 AND a.F_ParentId IN({ tempData });";

                    return db.FindList<AreaModel>(strSql);
                }
            }

            return new List<AreaModel>();
        }

        public AreaModel GetAreasByParentId(string areaId)
        {
            if (!areaId.IsNullOrEmpty())
            {
                return clientInfosApp.GetAllAreas().Where(p => p.F_EnCode == areaId).FirstOrDefault();
            }
            return default(AreaModel);
        }

        /// <summary>
        /// 关闭的订单
        /// </summary>
        public List<ClientOrderViewModel> GetCloseOrderList(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            var currentUser = OperatorProvider.Provider.GetCurrent();
            // 订单表(Site_Client_Order)的数据来源于需求表(Site_Clients_ProjectByDemand), 如果不一一配置那就说明数据删除过,不用处理。
            var sqlStr = @"SELECT sco.F_Id, 
		                        sco.F_DemandId, 
                                sco.F_WorkFormId,
		                        sco.F_FlowUserId, 
		                        sco.F_OrderState, 
		                        sco.F_OrderStateProcess, 
		                        sco.F_CreatorTime, 
		                        sco.F_LastModifyTime, 
                                sco.F_SignOut,
		                        scp.F_Source, 
		                        scp.F_ActivityTheme, 
		                        scp.F_ActivityType, 
		                        scp.F_DemandCash, 
		                        scp.F_ActivityStartDate, 
		                        scp.F_ActivityEndDate, 
		                        scp.F_ActivityCityId, 
		                        scp.F_SiteType, 
		                        scp.F_SiteArea, 
		                        scp.F_Mating, 
		                        scp.F_Intention, 
		                        scp.F_Note, 
		                        scp.F_State,                                 
		                        atype.F_ActivityTypeName, 
		                        su.F_RealName as 'F_FlowUserName', 
                                scpc.F_Contact, 
		                        sc.F_ClientName 
                            FROM Site_Client_Order sco
                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scp.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE sco.F_State=0";
            var dbParams = new MySqlParameter[] {
            };
            var countStr = @"SELECT COUNT(1) FROM Site_Client_Order sco ";

            if (!queryParam["keyword"].IsEmpty())
            {
                string keyword = queryParam["keyword"].ToString();
                sqlStr = $"{ sqlStr } AND scp.F_ActivityTheme LIKE '%{ keyword }%'";
            }
            if (!queryParam["orderstate"].IsEmpty())
            {
                string orderstate = queryParam["orderstate"].ToString();
                if (orderstate.IndexOf(',') == -1)
                {
                    sqlStr = $"{ sqlStr } AND sco.F_OrderState = { orderstate }";
                }
                else
                {
                    sqlStr = $"{ sqlStr } AND sco.F_OrderState in ({ orderstate })";
                }

            }
            int startNo = pagination.rows * (pagination.page - 1);
            int endNo = startNo + pagination.rows;

            sqlStr = $"{ sqlStr } ORDER BY sco.{ pagination.sidx } { pagination.sord } LIMIT { startNo },{ endNo };";

            var count = service.Count(countStr);
            pagination.records = count;

            using (var db = new RepositoryBase())
            {
                var result = db.FindList<ClientOrderViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        public List<ClientOrderViewModel> GetList(Pagination pagination, string queryJson, string type, string environment = "1")
        {
            var queryParam = queryJson.ToJObject();
            var currentUser = OperatorProvider.Provider.GetCurrent();

            using (var db = new RepositoryBase())
            {
                ///获取用户权限
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                RoleApp role = new RoleApp();
                RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
                OrganizeApp organize = new OrganizeApp();
                OrganizeEntity organizeEntity = organize.GetForm(LoginInfo.DepartmentId);

                string F_GroupId = "";
              

                // 订单表(Site_Client_Order)的数据来源于需求表(Site_Clients_ProjectByDemand), 如果不一一配置那就说明数据删除过,不用处理。
                var sqlStr = $@"SELECT sco.F_Id,sco.F_Id orderId, 
		                        sco.F_DemandId, 
                                sco.F_WorkFormId,
		                        sco.F_FlowUserId, 
		                        sco.F_OrderState, 
		                        sco.F_OrderStateProcess, 
		                        sco.F_CreatorTime, 
		                        sco.F_LastModifyTime, 
                                sco.F_SignOut,
		                        scp.F_Source, 
		                        scp.F_ActivityTheme, 
		                        scp.F_ActivityType, 
		                        scp.F_DemandCash, 
		                        scp.F_ActivityStartDate, 
		                        scp.F_ActivityEndDate, 
		                        scp.F_ActivityCityId, 
		                        scp.F_SiteType, 
		                        scp.F_SiteArea, 
		                        scp.F_Mating, 
		                        scp.F_Intention, 
		                        scp.F_Note, 
		                        scp.F_State,                                 
		                        atype.F_ActivityTypeName, 
		                        su.F_RealName as 'F_FlowUserName', 
                                scpc.F_Contact, 
		                        sc.F_ClientName ,
							    case 
                                    when srp.F_CreatorTime is not null or (sco.F_OrderState=9 and sco.F_OrderEnvironment=2) then 0    else 1 end reportState,
                                cge.F_ChangeReason
                            FROM Site_Client_Order sco
                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scp.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            left join (select rep.F_OrderId,max(rep.F_CreatorTime) F_CreatorTime from Site_Order_SalesReport rep group by F_OrderId) srp on srp.F_OrderId=sco.F_Id
                             LEFT JOIN Site_Client_OrderChangeRecord cge on sco.F_Id=cge.F_OrderId
                            WHERE sco.F_State=1 AND scp.F_State=1 and ifnull(sco.F_IsCheck,1)<>0 { F_GroupId }";

                var countStr = $@"SELECT COUNT(1) FROM Site_Client_Order sco
                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scp.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            left join (select rep.F_OrderId,max(rep.F_CreatorTime) F_CreatorTime from Site_Order_SalesReport rep group by F_OrderId) srp on srp.F_OrderId=sco.F_Id                            
                            WHERE sco.F_State=1 and ifnull(sco.F_IsCheck,1)<>0 AND scp.F_State=1 { F_GroupId }";

                if (!string.IsNullOrEmpty(type) && type == "self")
                {
                    sqlStr = $"{ sqlStr } AND sco.F_FlowUserId = '{ currentUser.UserId }'";
                    countStr += $@" AND sco.F_FlowUserId = '{ currentUser.UserId }'";
                }
                if (!queryParam["keyword"].IsEmpty())
                {
                    string keyword = queryParam["keyword"].ToString();
                    sqlStr = $"{ sqlStr } AND scp.F_ActivityTheme LIKE '%{ keyword }%' or scpc.F_Contact like '%{ keyword }%' or scpc.F_Phone like '%{ keyword }%'";
                    countStr = $"{ countStr } AND scp.F_ActivityTheme LIKE '%{ keyword }%' or scpc.F_Contact like '%{ keyword }%' or scpc.F_Phone like '%{ keyword }%'";
                }

                if (!queryParam["sourcetype"].IsEmpty())
                {
                    string sourcetype = queryParam["sourcetype"].ToString();
                    sqlStr = $"{ sqlStr } AND scp.F_Source = '{ sourcetype }'";
                    countStr = $"{ countStr } AND scp.F_Source = '{ sourcetype }'";
                }

                if (!queryParam["orderstate"].IsEmpty())
                {
                    string orderstate = queryParam["orderstate"].ToString();
                    if (orderstate == "9")
                    {
                        sqlStr = $"{ sqlStr } AND sco.F_OrderEnvironment = 3";
                        countStr = $"{ countStr } AND sco.F_OrderEnvironment = 3";
                    }
                    else {
                        sqlStr = $" { sqlStr } AND sco.F_OrderEnvironment = { environment } AND sco.F_OrderState = { orderstate } ";
                        countStr = $"{ countStr } AND sco.F_OrderEnvironment = { environment } AND sco.F_OrderState = { orderstate }";
                    }                    
                }
                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;

                sqlStr = $"{ sqlStr } ORDER BY sco.{ pagination.sidx } { pagination.sord } LIMIT { startNo },{ endNo };";

                var count = service.Count(countStr);
                pagination.records = count;

                var result = db.FindList<ClientOrderViewModel>(sqlStr);
                return result;
            }
        }
        /// <summary>
        /// 有效需求-导出demand Excel
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <returns></returns>
        public bool GetDemandToExcelData(string queryJson, string type, string environment = "1")
        {

            var queryParam = queryJson.ToJObject();
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var db = new RepositoryBase())
            {
                // 订单表(Site_Client_Order)的数据来源于需求表(Site_Clients_ProjectByDemand), 如果不一一配置那就说明数据删除过,不用处理。
                var sqlStr = $@"SELECT sco.F_Id, 
                                sco.F_WorkFormId,
		                        IFNULL(su.F_RealName,'') as 'F_FlowUserName',
		                        sco.F_CreatorTime, 
		                        IFNULL(scp.F_ActivityTheme, '') as F_ActivityTheme,
                                (SELECT group_concat(F_ItemName) FROM Sys_ItemsDetail  WHERE F_ItemId ='04ded926-33b1-4705-9070-41ff554acfd8' AND FIND_IN_SET(F_ItemCode,scp.F_SiteType))  as F_SiteType,
		                        IFNULL(scp.F_DemandCash, '') as F_DemandCash,
		                        scp.F_ActivityStartDate,
		                        scp.F_ActivityEndDate,
		                        (SELECT group_concat(sys.F_FullName) as F_FullName   FROM Sys_Area  sys  WHERE FIND_IN_SET (sys.F_Id,scp.F_ActivityCityId) )as  F_ActivityCityId, 
		                        IFNULL(scp.F_SiteArea,'') as F_SiteArea, 
		                        IFNULL(scp.F_Mating,'') as F_Mating,
		                        IFNULL(scp.F_Note,'') as F_Note, 
		                        scp.F_State,
                                CASE F_Source WHEN 0 THEN '400电话' WHEN 1 THEN '销售自拓' WHEN 2 THEN '网络订单'  END  as F_Source,
		                        IFNULL(atype.F_ActivityTypeName,'') as F_ActivityTypeName, 
                                IFNULL(scpc.F_Contact,'') as F_Contact, 
		                        IFNULL(sc.F_ClientName,'') as F_ClientName 
                            FROM Site_Client_Order sco
                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scp.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE sco.F_State=1 AND scp.F_State=1 AND sco.F_OrderEnvironment = { environment }";
                DbParameter[] parameter =
               {
                    new MySqlParameter("@F_ActivityCityId", queryParam["F_ActivityCityId"]),
                    new MySqlParameter("@F_ActivityType", queryParam["F_ActivityType"]),
                    new MySqlParameter("@F_DemandCash", queryParam["F_DemandCash"]),
                    new MySqlParameter("@F_ClientName", queryParam["F_ClientName"]),
                    new MySqlParameter("@F_ActivityStartDate", queryParam["F_ActivityStartDate"]),
                    new MySqlParameter("@F_CreatorTime", queryParam["F_CreatorTime"]),
                    new MySqlParameter("@F_Source", queryParam["F_Source"]),
                    new MySqlParameter("@F_State", queryParam["F_State"]),
                };
                sqlStr = string.Format(sqlStr,
                    queryParam["F_ActivityCityId"].IsEmpty() ? "" : " and a.F_ActivityCityId=@F_ActivityCityId",
                    queryParam["F_ActivityType"].IsEmpty() ? "" : " and a.F_ActivityType=@F_ActivityType",
                    queryParam["F_DemandCash"].IsEmpty() ? "" : " and a.F_DemandCash>=@F_DemandCash",
                    queryParam["F_ClientName"].IsEmpty() ? "" : " and c.F_Id=@F_ClientName",
                    queryParam["F_ActivityStartDate"].IsEmpty() ? "" : " and a.F_ActivityStartDate>=@F_ActivityStartDate",
                    queryParam["F_CreatorTime"].IsEmpty() ? "" : " and a.F_CreatorTime>=@F_CreatorTime",
                    queryParam["F_Source"].IsEmpty() ? "" : queryParam["F_Source"].ToString() == "-1" ? " and a.F_Source in(0,2)" : " and a.F_Source=@F_Source",
                    queryParam["F_State"].IsEmpty() ? "" : queryParam["F_State"].ToString() == "-1" ? "" : " and a.F_State=@F_State"
                    );

                var result = db.FindList<DemandToExcelEntity>(sqlStr);
                int resultCount = result.Count();

                DataTable dt = new DataTable(typeof(DemandToExcelEntity).Name);

                dt.Columns.Add("需求编号");
                dt.Columns.Add("F_WorkFormId");
                dt.Columns.Add("销售人员");
                dt.Columns.Add("创建时间");

                dt.Columns.Add("活动主题");
                dt.Columns.Add("活动类型");
                dt.Columns.Add("预算金额");
                dt.Columns.Add("活动开始时间");
                dt.Columns.Add("活动结束时间");
                dt.Columns.Add("活动城市");
                dt.Columns.Add("场地类型");
                dt.Columns.Add("场地面积");
                dt.Columns.Add("层高");
                dt.Columns.Add("配套服务");
                dt.Columns.Add("备注");
                dt.Columns.Add("联系人");
                dt.Columns.Add("客户名称");
                dt.Columns.Add("状态");
                dt.Columns.Add("来源");


                dt.Rows.Add("测试");

                PropertyInfo[] props = typeof(DemandToExcelEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                for (int i = 0; i < resultCount; i++)
                {
                    var item = result[i];

                    var values = new object[props.Length];
                    for (int j = 0; j < props.Length; j++)
                    {
                        values[j] = props[j].GetValue(item, null);
                    }
                    dt.Rows.Add(values);
                }

                NPOIExcel nPOIExcel = new NPOIExcel();


                string title = "有效需求数据" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";

                nPOIExcel.ExportWebExcel(dt, title);

                return false;
            }

        }



        public List<OrderCashViewModel> GetCashByOrder(Pagination pagination, string queryJson)
        {
            var currentUser = OperatorProvider.Provider.GetCurrent();
            var queryParam = queryJson.ToJObject();
            using (var db = new RepositoryBase())
            {
                string where = "";
                if (!queryParam["type"].IsEmpty() && queryParam["type"].ToString() == "1")
                {
                    where = " and s.F_FlowUserId='" + currentUser.UserId + "'";
                }
                if (!queryParam["keyword"].IsEmpty())
                {
                    where += " and sp.F_ActivityTheme like'%" + queryParam["keyword"].ToString() + "%'";
                }
                if (!queryParam["orderstate"].IsEmpty())
                {
                    where += " and sco.F_State='" + queryParam["orderstate"].ToString() + "'";
                }
                var strSql = $@"select sp.F_Id spid, sp.F_ActivityTheme,sp.F_ActivityCityId, concat(date_format(sp.F_ActivityStartDate, '%Y-%m-%d'),'~',date_format(sp.F_ActivityEndDate, '%Y-%m-%d')) as F_ActivityTime,
                             sco.* from Site_Client_Order s inner join Site_Clients_ProjectByDemand sp on sp.F_Id=s.F_DemandId inner join
                             (select distinct sc.F_ApplyType, so.* from Site_Client_OrderUsingPrice so inner join Sys_CheckRecord sc on so.F_No=sc.F_No where sc.F_ApplyType=6 and sc.F_State=1 ) sco 
                             on s.F_Id = sco.F_OrderId 
                             where ((s.F_OrderStateProcess=1 and s.F_OrderState=7)or (s.F_OrderState=8)) {where}  ";
                var countStr = $@"select count(1) from Site_Client_Order s inner join Site_Clients_ProjectByDemand sp on sp.F_Id=s.F_DemandId inner join
                             (select distinct sc.F_ApplyType, so.* from Site_Client_OrderUsingPrice so inner join Sys_CheckRecord sc on so.F_No=sc.F_No where sc.F_ApplyType=6 and sc.F_State=1 ) sco 
                             on s.F_Id = sco.F_OrderId 
                             where ((s.F_OrderStateProcess=1 and s.F_OrderState=7)or (s.F_OrderState=8)) {where}  ";
                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;

                strSql = $"{ strSql } ORDER BY sco.{ pagination.sidx } { pagination.sord } LIMIT { startNo },{ endNo };";

                var count = service.Count(countStr);
                pagination.records = count;
                return db.FindList<OrderCashViewModel>(strSql);
            }
        }

        /// <summary>
        /// 修改收支付状态
        /// </summary>
        /// <param name="keyValue"></param>
        public int UpdateCashState(string keyValue, int state, string no)
        {
            ClientOrderusingpriceEntity entity = new ClientOrderusingpriceEntity();
            using (var db = new RepositoryBase())
            {
                entity = db.FindEntity<ClientOrderusingpriceEntity>(keyValue);
                entity.F_State = state;
                entity.F_InvoiceNo = no;
                if (no != null && no != "")
                {
                    entity.F_InvoiceTime = DateTime.Now;
                }
                entity.Modify(keyValue);

                db.Update(entity);
                return 1;
            }
        }
        public OrderTagOutput GetOrderTags(string orderId)
        {
            var result = new OrderTagOutput();
            using (var db = new RepositoryBase())
            {
                var sqlStr = $@"SELECT t1.F_OrderId,t1.F_OrderState,
	                                CASE WHEN t2.F_OrderState IS NULL THEN 0 
		                                  WHEN t1.F_OrderState in(1,2) AND t1.F_OrderState = t2.F_OrderState AND t1.F_OrderStateProcess > 0 THEN 1
		                                  WHEN t1.F_OrderState in(3,4,5,6,7) AND t1.F_OrderState > t2.F_OrderState AND t1.F_OrderStateProcess in(-1)  THEN 1
	                                ELSE 0 END IsTag
                                FROM (SELECT F_Id F_OrderId,F_OrderState, F_OrderStateProcess FROM Site_Client_Order sco WHERE sco.F_OrderEnvironment=1 AND sco.F_State=1 AND sco.F_OrderState>0) t1
                                LEFT JOIN (SELECT scr.F_OrderId, max(scr.F_ApplyType) F_OrderState FROM Sys_CheckRecord scr where scr.F_State IS NOT NULL group by scr.F_OrderId) t2 
                                ON t1.F_OrderId = t2.F_OrderId
                                where t1.F_OrderId='{ orderId }'";
                var orderInfo = db.FindList<CheckRecordTodoDto>(sqlStr).FirstOrDefault();
                if (!orderInfo.IsEmpty())
                {
                    if (orderInfo.IsTag)
                    {
                        if (orderInfo.F_OrderState == 1)
                        {
                            var recommends = db.IQueryable<ClientOrderrecommendEntity>(p => p.F_OrderId == orderId).ToList();
                            result.AllStatusNum = recommends.Count();
                            if (recommends.Any())
                            {
                                result.SuccessStatusNum = recommends.Where(p => p.F_State == 1).Count();
                                result.ErrorStatusNum = recommends.Where(p => p.F_State == 2).Count();
                            }
                        }
                        else if (orderInfo.F_OrderState == 2)
                        {
                            var takelooks = db.IQueryable<ClientOrdertakelookEntity>(p => p.F_OrderId == orderId).ToList();
                            result.AllStatusNum = takelooks.Count();
                            if (takelooks.Any())
                            {
                                result.SuccessStatusNum = takelooks.Where(p => p.F_State == 1).Count();
                                result.ErrorStatusNum = takelooks.Where(p => p.F_State == 2).Count();
                            }
                        }
                        else
                        {
                            result.AllStatusNum = 1;
                        }
                    }
                    else
                    {
                        result.AllStatusNum = 1;
                    }
                }
            }

            return result;
        }

        public List<CheckRecordTodoDto> GetCheckRecordTodo(string type)
        {
            var currentUser = OperatorProvider.Provider.GetCurrent();

            var filters = new Dictionary<string, CheckRecordTodoDto>();
            var sqlStrWhere = type == "self" ? $"and sco.F_FlowUserId='{ currentUser.UserId }'" : "";

            // F_OrderState 1，2之后的逻辑是自动跳转的，所有订单记录表【Site_Client_Order】会比流程审核记录表【Sys_CheckRecord】中的值大1，所以减去
            var sqlStr = $@"-- 1. 审核表为空， 不显示提示
                            -- 2. 状态为推荐、带看时
                            SELECT t1.F_OrderId,t1.F_OrderState,
	                            CASE WHEN t2.F_OrderState IS NULL THEN 0 
		                              WHEN t1.F_OrderState in(1,2) AND t1.F_OrderState = t2.F_OrderState AND t1.F_OrderStateProcess > 0 THEN 1
		                              WHEN t1.F_OrderState in(3,4,5,6,7) AND t1.F_OrderState > t2.F_OrderState AND t1.F_OrderStateProcess in(-1)  THEN 1
	                            ELSE 0 END IsTag
                            FROM (SELECT F_Id F_OrderId,F_OrderState, F_OrderStateProcess FROM Site_Client_Order sco WHERE sco.F_OrderEnvironment=1 AND sco.F_State=1 AND sco.F_OrderState>0 { sqlStrWhere }) t1
                              LEFT JOIN (SELECT scr.F_OrderId, max(scr.F_ApplyType) F_OrderState FROM Sys_CheckRecord scr where scr.F_State IS NOT NULL group by scr.F_OrderId) t2 
                              ON t1.F_OrderId = t2.F_OrderId;";

            using (var db = new RepositoryBase())
            {
                return db.FindList<CheckRecordTodoDto>(sqlStr);
            }
        }

        /// <summary>
        /// 修改需求信息（在流程流转过程中）
        /// </summary>
        public void SubmitBaseDemandForm(OrderInfoInput orderInfo, string keyValue)
        {
            var demandId = orderInfo.DemandId;
            var contactId = orderInfo.ContactId;
            var projectId = orderInfo.ProjectId;
            var clientId = orderInfo.ClientId;

            using (var db = new RepositoryBase().BeginTrans())
            {
                if (!demandId.IsNullOrEmpty())
                {
                    var demandEntity = db.FindEntity<SiteClientsProjectByDemandEntity>(demandId);
                    // 1. 更新需求信息
                    if (!demandEntity.IsEmpty())
                    {
                        demandEntity.F_ActivityTheme = orderInfo.F_ActivityTheme;
                        demandEntity.F_ActivityCityId = string.Join(",", orderInfo.F_ActivityCityId);
                        demandEntity.F_BuildDate = orderInfo.F_BuildDate;
                        demandEntity.F_ActivityType = orderInfo.F_ActivityType;
                        demandEntity.F_ActivityStartDate = orderInfo.F_ActivityStartDate;
                        demandEntity.F_ActivityEndDate = orderInfo.F_ActivityEndDate;
                        demandEntity.F_SiteArea = orderInfo.F_SiteArea;
                        demandEntity.F_PersionNumber = orderInfo.F_PersionNumber;
                        demandEntity.F_Height = orderInfo.F_Height;

                        demandEntity.F_DemandCash = orderInfo.F_DemandCash;
                        demandEntity.F_Note = orderInfo.F_Note;

                        demandEntity.Modify(demandId);
                        db.Update<SiteClientsProjectByDemandEntity>(demandEntity);
                    }
                }
                if (!contactId.IsNullOrEmpty())
                {
                    // 2. 更新联系人信息
                    var contactEntity = db.FindEntity<SiteClientsProjectByContactEntity>(contactId);
                    if (!contactEntity.IsEmpty())
                    {
                        contactEntity.F_Contact = orderInfo.F_Contact;
                        contactEntity.F_DepartmentId = orderInfo.F_DepartmentId;
                        contactEntity.F_PositionId = orderInfo.F_PositionId;
                        contactEntity.F_Phone = orderInfo.F_Phone;
                        contactEntity.F_Mail = orderInfo.F_Mail;

                        contactEntity.Modify(contactId);
                        db.Update<SiteClientsProjectByContactEntity>(contactEntity);
                    }
                }
                if (!projectId.IsNullOrEmpty())
                {
                    // 3. 更新客户品牌项目组信息
                    var projectEntity = db.FindEntity<SiteClientsAllProjectsEntity>(projectId);
                    if (!projectEntity.IsEmpty())
                    {
                        if (projectEntity.F_ProjectName != orderInfo.F_ProjectName)
                        {
                            projectEntity.F_ProjectName = orderInfo.F_ProjectName;
                            projectEntity.Modify(projectId);
                            db.Update<SiteClientsAllProjectsEntity>(projectEntity);
                        }
                    }
                }

                if (!clientId.IsNullOrEmpty())
                {
                    // 更新公司相关信息
                    var clientEntity = db.FindEntity<SiteClientsEntity>(clientId);
                    if (clientEntity.F_ClientName != orderInfo.F_ClientName)
                    {
                        clientEntity.F_ClientName = orderInfo.F_ClientName;
                        clientEntity.Modify(clientId);
                        db.Update<SiteClientsEntity>(clientEntity);
                    }
                }
                db.Commit();
            }
        }

        public List<ClientSiteViewModel> GetSiteList(Pagination pagination, string queryJson)
        {
            var queryParam = queryJson.ToJObject();
            using (var db = new RepositoryBase())
            {
                var sqlStr = @"SELECT   site.F_Id F_SiteId, 
                                    site.title F_SiteName, 
                                    site.site_type F_SiteType, 
                                    site.city_id F_CityId,
                                    site.district_id F_DistrictId,
                                    site.business_area F_BusinessArea,
                                    asite.F_SiteTypeName, 
                                    space1.F_Id F_SpaceId,
                                    space1.title F_SpaceName,
			                        space1.F_Units, 
                                    site.second_type F_SecondType, 
                                    -- site.recommend_reason F_Reason, 
                                    -- site.address F_Address, 
                                    -- site.F_Attachment,
                                    site.F_AttachmentPpt,
                                    IFNULL(space1.F_YunPrice, 0) F_YunPrice, 
                                    IFNULL(space1.F_MarketPrice, 0) F_MarketPrice, 
                                    IFNULL(space1.max_seating_capacity, 0) F_MaxPeople, 
                                    IFNULL(space1.area, 0) F_Area
                          FROM SL_Site site
                          INNER JOIN SL_Space space1 ON site.F_Id = space1.F_SiteId
                          LEFT JOIN (select sid.F_ItemCode as 'F_SiteType', sid.F_ItemName as 'F_SiteTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='SiteType') asite ON site.site_type = asite.F_SiteType
                          WHERE site.state = 1 AND space1.state = 1";

                var otherSqlStr = "";
                if (!queryParam["keyword"].IsEmpty())
                {
                    string keyword = queryParam["keyword"].ToString();
                    otherSqlStr = string.Format(@"{0} AND (site.title like '%{1}%'
								  OR site.address like '%{1}%' OR site.recommend_reason like '%{1}%')", otherSqlStr, keyword);
                }
                else
                {
                    if (!queryParam["sitetype"].IsEmpty())
                    {
                        string sitetype = queryParam["sitetype"].ToString();
                        otherSqlStr = string.Format("{0} AND site.site_type in ({1})", otherSqlStr, sitetype);
                    }
                    if (!queryParam["acttype"].IsEmpty())
                    {
                        string acttype = queryParam["acttype"].ToString();
                        if (acttype.Length == 4)
                        {
                            var aStrSql = $@"select sid.F_ItemCode Value from Sys_Items si 
										 left join Sys_ItemsDetail sid on si.F_Id = sid.F_ItemId
										 where si.F_EnCode='ActivityType' AND sid.F_Description='{ acttype }'";
                            var childs = db.FindList<SelectListItemViewModel>(aStrSql);
                            var acttypes = string.Join(",", childs.Select(p => p.Value));
                            otherSqlStr = string.Format("{0} AND site.site_event_type in ({1})", otherSqlStr, acttypes);
                        }
                        else
                        {
                            otherSqlStr = string.Format("{0} AND site.site_event_type like '%{1}%'", otherSqlStr, acttype);
                        }

                    }
                    if (!queryParam["cityid"].IsEmpty())
                    {
                        string cityid = queryParam["cityid"].ToString();
                        otherSqlStr = string.Format("{0} AND site.city_id in({1})", otherSqlStr, cityid);
                    }
                    if (!queryParam["districtid"].IsEmpty())
                    {
                        string districtid = queryParam["districtid"].ToString();
                        otherSqlStr = string.Format("{0} AND site.district_id in({1})", otherSqlStr, districtid);
                    }
                    if (!queryParam["businessarea"].IsEmpty())
                    {
                        string businessarea = string.Join(",", queryParam["businessarea"].ToString().Split(',').Select(p => $"'{ p }'"));
                        otherSqlStr = string.Format("{0} AND site.business_area in({1})", otherSqlStr, businessarea);
                    }

                    if (!queryParam["area"].IsEmpty())
                    {
                        string area = queryParam["area"].ToString();
                        otherSqlStr = string.Format("{0} AND space1.area >= {1}", otherSqlStr, area);
                    }
                    if (!queryParam["minmoney"].IsEmpty())
                    {
                        string minmoney = queryParam["minmoney"].ToString();
                        otherSqlStr = string.Format("{0} AND space1.F_MarketPrice >= {1}", otherSqlStr, minmoney);
                    }

                    if (!queryParam["maxmoney"].IsEmpty())
                    {
                        string maxmoney = queryParam["maxmoney"].ToString();
                        otherSqlStr = string.Format("{0} AND space1.F_MarketPrice <= {1}", otherSqlStr, maxmoney);
                    }
                }

                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;
                sqlStr = $"{ sqlStr } { otherSqlStr } ORDER BY site.{ pagination.sidx } { pagination.sord } LIMIT { startNo },{ endNo };";

                var count = service.Count($"SELECT COUNT(1) FROM SL_Site site INNER JOIN SL_Space space1 ON site.F_Id = space1.F_SiteId WHERE site.state = 1 AND space1.state = 1 { otherSqlStr };");
                pagination.records = count;

                var result = db.FindList<ClientSiteViewModel>(sqlStr);
                return result;
            }
        }

        public bool SubmitTakelookFeelback(OrderTakelookFeelbackInput orderTakelookFeelbackEntity, string keyValue)
        {
            var result = false;
            var orderId = orderTakelookFeelbackEntity.OrderId;
            var no = orderTakelookFeelbackEntity.No;

            using (var db = new RepositoryBase().BeginTrans())
            {
                var takeLookfeedbacks = takeLookfeedbackService.IQueryable(p => p.F_OrderId == orderId && p.F_No == no).ToList();
                if (!takeLookfeedbacks.Any())
                {
                    var takelooks = takelookService.IQueryable(p => p.F_OrderId == orderId && p.F_No == no && p.F_State == 1).ToList();
                    if (takelooks.Any())
                    {
                        var first = orderTakelookFeelbackEntity.Data.FirstOrDefault();
                        if (!first.IsEmpty())
                        {
                            result = true;
                            takelooks.ForEach(takelook =>
                            {
                                var entity = new SiteOrderTakeLookfeedbackEntity
                                {
                                    F_No = takelook.F_No,
                                    F_OrderId = orderId,
                                    F_SiteId = takelook.F_SiteId,
                                    F_SpaceId = takelook.F_SpaceId,
                                    F_Reason = first.F_Reason,
                                    F_Remark = first.F_Remark
                                };
                                entity.Create();

                                db.Insert<SiteOrderTakeLookfeedbackEntity>(entity);
                            });
                        }

                    }
                }

                var orderEntity = db.FindEntity<ClientOrderEntity>(orderId);
                orderEntity.F_OrderState = 3;
                orderEntity.F_OrderStateProcess = -1;
                orderEntity.Modify(keyValue);
                db.Update<ClientOrderEntity>(orderEntity);

                db.Commit();
            }

            return result;
        }

        /// <summary>
        /// 获取需求预定信息
        /// </summary>
        private SiteClientsProjectByDemandEntity GetDemandOrderByOrderId(string orderId)
        {
            using (var db = new RepositoryBase())
            {
                var sqlDemandOrderStr = $@"SELECT SCPD.* FROM Site_Clients_ProjectByDemand SCPD
		                                           INNER JOIN Site_Client_Order SCO ON SCPD.F_Id = SCO.F_DemandId
		                                           WHERE SCO.F_Id='{ orderId }'";
                var demandOrder = db.FindList<SiteClientsProjectByDemandEntity>(sqlDemandOrderStr).FirstOrDefault();

                return demandOrder;
            }
        }

        /// <summary>
        /// 更新推荐流程
        /// </summary>
        /// <param name="keyValue"></param>
        public void SendSiteFlow(string keyValue)
        {
            var entity = service.FindEntity(keyValue);
            entity.F_OrderState = 2;
            entity.F_OrderStateProcess = -1;
            entity.Modify(keyValue);

            service.Update(entity);
        }

        /// <summary>
        /// 更新推荐流程
        /// </summary>
        /// <param name="keyValue"></param>
        public void IntentionSiteFlow(string keyValue)
        {
            var entity = service.FindEntity(keyValue);
            entity.F_OrderState = 4;
            entity.F_OrderStateProcess = -1;
            entity.Modify(keyValue);

            service.Update(entity);
        }

        public bool CreatePriceTalksFlow(string randomNo, OrderSitesFlowInput input, string keyValue)
        {
            var result = false;
            var orderId = input.OrderId;
            IEnumerable<string> siteAndSpaceIds = input.SiteIds;
            var demandOrder = GetDemandOrderByOrderId(orderId);
            if (demandOrder != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var sqlStr = $@"SELECT * FROM Site_Client_OrderPriceTalks WHERE F_OrderId='{ orderId }'";
                    var existPriceTalks = db.FindList<ClientOrderpricetalksEntity>(sqlStr);
                    if (existPriceTalks.Any())
                    {
                        var existIds = existPriceTalks.Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }");
                        siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                    }
                    // 相关推荐场地没有已推荐过的场地
                    result = input.SiteIds.Count == siteAndSpaceIds.Count();

                    if (input.SiteIds.Any() && result)
                    {
                        input.SiteIds.ForEach(siteAndSpaceId =>
                        {
                            var siteId = siteAndSpaceId.Split('|')[0];
                            var spaceId = siteAndSpaceId.Split('|')[1];

                            var entity = new ClientOrderpricetalksEntity
                            {
                                F_No = randomNo,
                                F_OrderId = input.OrderId,
                                F_SiteId = siteId,
                                F_SpaceId = spaceId,
                                F_StartDate = demandOrder.F_ActivityStartDate,
                                F_EndDate = demandOrder.F_ActivityEndDate,
                                F_State = 0
                            };
                            entity.Create();
                            db.Insert<ClientOrderpricetalksEntity>(entity);

                            var orderEntity = db.FindEntity<ClientOrderEntity>(keyValue);
                            if (orderEntity != null)
                            {
                                //orderEntity.F_OrderState = 4;
                                orderEntity.F_OrderStateProcess = 0;
                                orderEntity.Modify(keyValue);

                                db.Update(orderEntity);
                            }

                            db.Commit();
                        });
                    }
                }
            }

            return result;
        }

        public void SubmitPriceDetail(OrderPriceDetailInput input)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                input.Data.ForEach(item =>
                {
                    var entity = db.FindEntity<ClientOrderPriceDetailEntity>(item.F_Id);
                    if (!entity.IsEmpty())
                    {
                        //entity.F_YunPrice = item.YunPrice;
                        entity.F_SalePrice = item.SalePrice;
                        entity.F_TotalPrice = item.TotalPrice;

                        entity.Modify(item.F_Id);
                        db.Update<ClientOrderPriceDetailEntity>(entity);
                    }
                });

                db.Commit();
            }
        }

        public List<OrderPriceDetailOutput> GetPriceDetailList(string keyValue, string siteId, string spaceId)
        {
            using (var db = new RepositoryBase())
            {
                var sqlStr = $@"select scop.*, 
		                                site.title F_SiteName, 
		                                space.title F_SpaceName,
		                                fylm.F_ItemName F_FeeTypeName,
		                                units.F_ItemName F_UnitName
                                from Site_Client_OrderPriceDetail scop
                                inner join SL_Site site on scop.F_SiteId = site.F_Id
                                inner join SL_Space space on scop.F_SiteId = space.F_SiteId and scop.F_SpaceId=space.F_Id 
                                left join (select sid.F_ItemCode, sid.F_ItemName from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='fylm') fylm ON scop.F_FeeType = fylm.F_ItemCode
                                left join (select sid.F_ItemCode, sid.F_ItemName from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='units') units ON scop.F_Unit = units.F_ItemCode
                                where scop.F_OrderId='{ keyValue }' and scop.F_SiteId='{ siteId }' and scop.F_SpaceId='{ spaceId }'";
                var result = db.FindList<OrderPriceDetailOutput>(sqlStr);

                return result;
            }
        }

        public bool SubmitPriceTalksFlow(OrderSitesFlowInput input, string keyValue)
        {
            var result = false;

            using (var db = new RepositoryBase())
            {
                // 根据审核记录来确认相关价格审核是否已发布
                var sqlStr = $@"select 1 from Sys_CheckRecord where F_No='{ input.No }' AND F_ApplyType=4 AND F_OrderId='{ input.OrderId }';";
                var count = db.Count(sqlStr);
                if (count <= 0)
                {
                    var entity = service.FindEntity(keyValue);
                    if (!entity.IsEmpty())
                    {
                        result = true;

                        entity.F_OrderStateProcess = 0;
                        entity.Modify(keyValue);
                        service.Update(entity);
                    }
                }
            }

            return result;
        }

        //public void ReserveSiteFlow(string keyValue)
        //{
        //    var entity = service.FindEntity(keyValue);
        //    entity.F_OrderState = 6;
        //    entity.F_OrderStateProcess = -1;
        //    entity.Modify(keyValue);

        //    service.Update(entity);
        //}

        //public void SignContractFlow(string keyValue)
        //{
        //    var entity = service.FindEntity(keyValue);
        //    entity.F_OrderState = 7;
        //    entity.F_OrderStateProcess = 1;
        //    entity.Modify(keyValue);

        //    service.Update(entity);
        //}

        //public void StopContractFlow(string keyValue)
        //{
        //    var entity = service.FindEntity(keyValue);
        //    entity.F_OrderState = 7;
        //    entity.F_OrderStateProcess = 2;
        //    entity.Modify(keyValue);

        //    service.Update(entity);
        //}

        /// <summary>
        /// 回退到推荐场地
        /// </summary>
        /// <param name="keyValue"></param>
        public void BackSendSiteFlow(string keyValue)
        {
            var entity = service.FindEntity(keyValue);
            entity.F_OrderState = 1;
            entity.F_OrderStateProcess = -1;
            entity.Modify(keyValue);

            service.Update(entity);
        }

        public void SubmitPreviewPeopleForm(OrderTakelookDetailPeopleInput orderTakelookPeopleEntity, string keyValue)
        {
            if (!orderTakelookPeopleEntity.Data.IsEmpty())
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    foreach (var strJson in orderTakelookPeopleEntity.Data)
                    {
                        var entity = new ClientOrdertakelookDetailEntity
                        {
                            F_OrderId = orderTakelookPeopleEntity.OrderId,
                            F_SiteId = orderTakelookPeopleEntity.SiteId,
                            F_SpaceId = orderTakelookPeopleEntity.SpaceId,
                            F_SourceType = 3,
                            F_Source = strJson
                        };
                        entity.Create();
                        db.Insert<ClientOrdertakelookDetailEntity>(entity);
                    }
                    db.Commit();
                }
            }
        }

        public void SubmitPreviewCarForm(OrderTakelookDetailCarInput orderTakelookCarEntity, string keyValue)
        {
            if (!orderTakelookCarEntity.Data.IsEmpty())
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    foreach (var strJson in orderTakelookCarEntity.Data)
                    {
                        var entity = new ClientOrdertakelookDetailEntity
                        {
                            F_OrderId = orderTakelookCarEntity.OrderId,
                            F_SiteId = orderTakelookCarEntity.SiteId,
                            F_SpaceId = orderTakelookCarEntity.SpaceId,
                            F_SourceType = 2,
                            F_Source = strJson
                        };
                        entity.Create();
                        db.Insert<ClientOrdertakelookDetailEntity>(entity);
                    }
                    db.Commit();
                }
            }
        }



        public bool SubmitPreviewTimeForm(OrderTakelookDetailTimeInput oEntity, string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                var first = db.IQueryable<ClientOrdertakelookDetailEntity>(p => p.F_OrderId == oEntity.OrderId && p.F_SiteId == oEntity.SiteId && p.F_SpaceId == oEntity.SpaceId && p.F_SourceType == 1).FirstOrDefault();
                if (first.IsEmpty())
                {
                    var entity = new ClientOrdertakelookDetailEntity
                    {
                        F_OrderId = oEntity.OrderId,
                        F_SiteId = oEntity.SiteId,
                        F_SpaceId = oEntity.SpaceId,
                        F_SourceType = 1,
                        F_Source = string.Concat("{ \"startTime\":\"", oEntity.F_StartTime, "\", \"endTime\":\"", oEntity.F_EndTime, "\" }")
                    };
                    entity.Create();
                    db.Insert<ClientOrdertakelookDetailEntity>(entity);
                }
                return first.IsEmpty();
            }
        }

        public bool SubmitTakelookForm(OrderSitesFlowInput orderTakelookEntity, string keyValue)
        {
            var result = false;
            var orderId = orderTakelookEntity.OrderId;
            IEnumerable<string> siteAndSpaceIds = orderTakelookEntity.SiteIds;

            using (var db = new RepositoryBase().BeginTrans())
            {
                var sqlStr = $@"SELECT * FROM Site_Client_OrderTakelook WHERE F_OrderId='{ keyValue }' AND F_No='{ orderTakelookEntity.No }'";
                var existTakeLooks = db.FindList<ClientOrdertakelookEntity>(sqlStr);
                if (existTakeLooks.Any())
                {
                    var existIds = existTakeLooks.Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }|{ p.F_No }");
                    siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                }
                // 相关推荐场地没有已推荐过的场地
                result = orderTakelookEntity.SiteIds.Count == siteAndSpaceIds.Count();

                if (result)
                {
                    // 只有推荐成功的记录才可以带看（F_State == 1）
                    var recommends = recommendService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == orderTakelookEntity.No && p.F_State == 1).ToList();
                    if (recommends.Any())
                    {
                        recommends.ForEach(recommend =>
                        {
                            var entity = new ClientOrdertakelookEntity
                            {
                                F_No = recommend.F_No,
                                F_OrderId = keyValue,
                                F_SiteId = recommend.F_SiteId,
                                F_SpaceId = recommend.F_SpaceId,
                                F_State = 0
                            };
                            entity.Create();

                            db.Insert<ClientOrdertakelookEntity>(entity);
                        });
                    }

                    var orderEntity = db.FindEntity<ClientOrderEntity>(keyValue);
                    //orderEntity.F_OrderState = 2;// 3;
                    orderEntity.F_OrderStateProcess = 0;// -1;
                    orderEntity.Modify(keyValue);
                    db.Update<ClientOrderEntity>(orderEntity);

                    db.Commit();
                }
            }

            return result;
        }

        public bool SubmitReserveSiteForm(OrderSitesFlowInput input, string keyValue)
        {
            var result = false;
            var orderId = input.OrderId;
            IEnumerable<string> siteAndSpaceIds = input.SiteIds;

            var demandOrder = GetDemandOrderByOrderId(orderId);
            if (demandOrder != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var sqlStr = $@"SELECT * FROM Site_Client_OrderReserve WHERE F_OrderId='{ orderId }' AND F_No ='{ input.No }'";
                    var existReserves = db.FindList<ClientOrderreserveEntity>(sqlStr);
                    if (existReserves.Any())
                    {
                        var existIds = existReserves.Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }|{ p.F_No }");
                        siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                    }
                    // 相关推荐场地没有已推荐过的场地
                    result = input.SiteIds.Count == siteAndSpaceIds.Count();

                    if (result)
                    {
                        var intentions = intentionService.IQueryable(p => p.F_OrderId == orderId && p.F_No == input.No).ToList();
                        if (intentions.Any())
                        {
                            intentions.ForEach(intention =>
                            {
                                var entity = new ClientOrderreserveEntity
                                {
                                    F_No = intention.F_No,
                                    F_OrderId = keyValue,
                                    F_SiteId = intention.F_SiteId,
                                    F_SpaceId = intention.F_SpaceId,
                                    F_StartDate = demandOrder.F_ActivityStartDate,
                                    F_EndDate = demandOrder.F_ActivityEndDate,
                                    F_State = 0,
                                    F_ReserveTime = DateTime.Now
                                };
                                entity.Create();

                                db.Insert<ClientOrderreserveEntity>(entity);
                            });

                            var orderEntity = db.FindEntity<ClientOrderEntity>(keyValue);
                            //orderEntity.F_OrderState = 6;
                            if (orderEntity != null)
                            {
                                orderEntity.F_OrderStateProcess = 0;
                                orderEntity.Modify(keyValue);
                                db.Update<ClientOrderEntity>(orderEntity);
                            }
                        }
                    }
                    db.Commit();
                }
            }

            return result;
        }

        public List<OrderImpressOutput> GetImpressGrid(string orderId)
        {
            var strSql = $@"SELECT SCOR.F_OrderId,
                                   SCOR.F_No,
                                   SCOR.F_SiteId,
                                   SCOR.F_SpaceId,
                                   site.title F_SiteName,
                                   space.title F_SpaceName,
                                   SCOI.F_ClientFileName,
                                   SCOI.F_ClientFileCode,
                                   SCOI.F_ClientSignDate,
                                   SCOI.F_ClientFilePath,
                                   SCOI.F_SiteFileName,
                                   SCOI.F_SiteFileCode,
                                   SCOI.F_SiteSignDate,
                                   SCOI.F_SiteFilePath,
                                   SCOI.F_State,
                                   SCOI.F_CreatorTime
                            FROM Site_Client_OrderReserve SCOR
                            LEFT JOIN Site_Client_OrderImpress SCOI ON SCOR.F_OrderId = SCOI.F_OrderId AND SCOR.F_No = SCOI.F_No AND SCOR.F_SiteId = SCOI.F_SiteId AND SCOR.F_SpaceId = SCOI.F_SpaceId 
                            INNER JOIN SL_Site site on SCOR.F_SiteId = site.F_Id
                            INNER JOIN SL_Space space on SCOR.F_SiteId = space.F_SiteId and SCOR.F_SpaceId=space.F_Id 
                            WHERE (SCOR.F_State is null or SCOR.F_State in(0,1)) AND SCOR.F_OrderId = '{ orderId }' ORDER BY SCOR.F_No";

            using (var db = new RepositoryBase())
            {
                return db.FindList<OrderImpressOutput>(strSql);
            }
        }

        public void SubmitClientFileImpress(UpdateSignContractFileInput entity, string keyValue)
        {
            var siteAndSpaceId = entity.SiteAndSpaceId;
            var no = entity.No;
            var siteId = siteAndSpaceId.Split('|')[0];
            var spaceId = siteAndSpaceId.Split('|')[1];

            var demandOrder = GetDemandOrderByOrderId(keyValue);
            if (!demandOrder.IsEmpty())
            {
                var impresses = impressService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                if (impresses.Any())
                {
                    impresses.ForEach(impress =>
                    {

                        impress.F_ClientFileName = entity.FileName;
                        impress.F_ClientFileType = entity.FileType;
                        impress.F_ClientFilePath = entity.FilePath;
                        impress.F_ClientSignDate = entity.FileDate;
                        impress.F_ClientFileCode = entity.FileCode;
                        impress.Modify(impress.F_Id);

                        impressService.Update(impress);
                    });
                }
                else
                {
                    var reserves = reserveService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                    reserves.ForEach(reserve =>
                    {
                        var impress = new ClientOrderimpressEntity
                        {
                            F_No = no,
                            F_OrderId = keyValue,
                            F_SiteId = reserve.F_SiteId,
                            F_SpaceId = reserve.F_SpaceId,
                            F_ClientFileName = entity.FileName,
                            F_ClientFileType = entity.FileType,
                            F_ClientFilePath = entity.FilePath,
                            F_ClientFileCode = entity.FileCode,
                            F_ClientSignDate = entity.FileDate,
                            F_State = -1
                        };
                        impress.Create();
                        impressService.Insert(impress);
                    });
                }
            }
        }

        public void SubmitSiteFileImpress(UpdateSignContractFileInput entity, string keyValue)
        {
            var siteAndSpaceId = entity.SiteAndSpaceId;
            var no = entity.No;
            var siteId = siteAndSpaceId.Split('|')[0];
            var spaceId = siteAndSpaceId.Split('|')[1];

            var demandOrder = GetDemandOrderByOrderId(keyValue);
            if (!demandOrder.IsEmpty())
            {
                var impresses = impressService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                if (impresses.Any())
                {
                    impresses.ForEach(impress =>
                    {

                        impress.F_SiteFileName = entity.FileName;
                        impress.F_SiteFileType = entity.FileType;
                        impress.F_SiteFilePath = entity.FilePath;
                        impress.F_SiteSignDate = entity.FileDate;
                        impress.F_SiteFileCode = entity.FileCode;
                        impress.Modify(impress.F_Id);

                        impressService.Update(impress);
                    });
                }
                else
                {
                    var reserves = reserveService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                    reserves.ForEach(reserve =>
                    {
                        var impress = new ClientOrderimpressEntity
                        {
                            F_No = no,
                            F_OrderId = keyValue,
                            F_SiteId = reserve.F_SiteId,
                            F_SpaceId = reserve.F_SpaceId,
                            F_SiteFileName = entity.FileName,
                            F_SiteFileType = entity.FileType,
                            F_SiteFilePath = entity.FilePath,
                            F_SiteFileCode = entity.FileCode,
                            F_SiteSignDate = entity.FileDate,
                            F_State = -1
                        };
                        impress.Create();
                        impressService.Insert(impress);
                    });
                }
            }
        }

        public void SubmitFileSignContract(UpdateSignContractFileInput entity, string keyValue)
        {
            var siteAndSpaceId = entity.SiteAndSpaceId;
            var no = entity.No;
            var siteId = siteAndSpaceId.Split('|')[0];
            var spaceId = siteAndSpaceId.Split('|')[1];

            var demandOrder = GetDemandOrderByOrderId(keyValue);
            if (!demandOrder.IsEmpty())
            {
                var signContracts = signContractService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                if (signContracts.Any())
                {
                    signContracts.ForEach(signContract =>
                    {

                        signContract.F_FileName = entity.FileName;
                        signContract.F_FileType = entity.FileType;
                        signContract.F_FilePath = entity.FilePath;
                        signContract.F_StartDate = demandOrder.F_ActivityStartDate;
                        signContract.F_EndDate = demandOrder.F_ActivityEndDate;

                        signContract.Modify(signContract.F_Id);

                        signContractService.Update(signContract);
                    });
                }
                else
                {
                    var reserves = reserveService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == no).ToList();
                    reserves.ForEach(reserve =>
                    {
                        var signContract = new ClientOrdersigncontractEntity
                        {
                            F_No = no,
                            F_OrderId = keyValue,
                            F_SiteId = reserve.F_SiteId,
                            F_SpaceId = reserve.F_SpaceId,
                            F_FileName = entity.FileName,
                            F_FileType = entity.FileType,
                            F_FilePath = entity.FilePath,
                            F_StartDate = demandOrder.F_ActivityStartDate,
                            F_EndDate = demandOrder.F_ActivityEndDate,
                            F_State = -1
                        };
                        signContract.Create();
                        signContractService.Insert(signContract);
                    });
                }
            }
        }

        public bool SubmitImpressForm(string randomNo, OrderImpressInput entity, string keyValue)
        {
            var result = false;
            using (var db = new RepositoryBase().BeginTrans())
            {
                var orderInfo = db.FindEntity<ClientOrderEntity>(keyValue);
                if (orderInfo != null)
                {
                    if (orderInfo.F_OrderStateProcess == -1)
                    {
                        entity.OrderUsings.ForEach(usingEntity =>
                        {
                            usingEntity.F_No = randomNo;

                            usingEntity.Create();
                            db.Insert<ClientOrderusingEntity>(usingEntity);
                        });
                        entity.OrderUsingPrices.ForEach(usingPriceEntity =>
                        {
                            usingPriceEntity.F_No = randomNo;

                            usingPriceEntity.Create();
                            usingPriceEntity.F_State = 0;
                            db.Insert<ClientOrderusingpriceEntity>(usingPriceEntity);
                        });

                        orderInfo.F_OrderStateProcess = 0;
                        orderInfo.Modify(keyValue);

                        db.Update<ClientOrderEntity>(orderInfo);
                        db.Commit();

                        result = true;
                    }
                }
            }
            return result;
        }


        public List<SelectListItemViewModel> GetReserveSiteByOrder(string orderId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = $@"SELECT CONCAT(SITE.title, '-', SPACE.title) Text, CONCAT(SITE.title, '-', SPACE.title) Value
                                    FROM Site_Client_OrderReserve SCOR
			                        LEFT JOIN SL_Site SITE ON SCOR.F_SiteId = SITE.F_Id
			                        LEFT JOIN SL_Space SPACE ON SCOR.F_SpaceId = SPACE.F_Id
                            WHERE SCOR.F_State=1 AND SCOR.F_OrderId = '{ orderId }'";
                return db.FindList<SelectListItemViewModel>(strSql);
            }
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        public bool GetFileExistSignContract(string orderId, string no)
        {
            var sqlStr = $@"SELECT * FROM Site_Client_OrderSignContract scosc WHERE scosc.F_OrderId='{ orderId }' AND scosc.F_No='{ no }'";
            using (var db = new RepositoryBase())
            {
                var existSignContract = db.FindList<ClientOrdersigncontractEntity>(sqlStr).FirstOrDefault();
                if (existSignContract.IsEmpty())
                {
                    return false;
                }

                return existSignContract.F_FilePath.Trim().Length != 0;
            }
        }

        public bool GetFileExist(string orderId)
        {
            var sqlStr = $@"SELECT * FROM Site_Client_OrderImpress scosc WHERE scosc.F_OrderId='{ orderId }'";
            using (var db = new RepositoryBase())
            {
                var existSignContract = db.FindList<ClientOrderimpressEntity>(sqlStr).FirstOrDefault();
                if (existSignContract.IsEmpty())
                {
                    return false;
                }

                return existSignContract.F_ClientFilePath.IsNullOrEmpty() ||  existSignContract.F_SiteFilePath.IsNullOrEmpty();
            }
        }

        public bool SubmitSignContractForm(OrderSitesFlowInput input, string keyValue)
        {
            var result = false;
            var orderId = input.OrderId;
            IEnumerable<string> siteAndSpaceIds = input.SiteIds;
            var demandOrder = GetDemandOrderByOrderId(orderId);
            if (demandOrder != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var sqlStr = $@"SELECT * FROM Site_Client_OrderSignContract scosc WHERE scosc.F_OrderId='{ orderId }' AND scosc.F_No='{ input.No }'";
                    var existSignContracts = db.FindList<ClientOrdersigncontractEntity>(sqlStr);
                    if (existSignContracts.Any())
                    {
                        // 判断 F_State 是否大于等于 0， 小于0的状态为上传文件生成的相关合同信息
                        var existIds = existSignContracts.Where(p => p.F_State >= 0).Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }|{ p.F_No }");
                        siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                    }
                    // 相关推荐场地没有已推荐过的场地
                    result = input.SiteIds.Count == siteAndSpaceIds.Count();

                    if (result)
                    {
                        // 判断是新增或修改信息
                        var signContracts = existSignContracts.Where(p => p.F_OrderId == orderId && p.F_No == input.No).ToList();
                        if (signContracts.Any())
                        {
                            signContracts.ForEach(signContract =>
                            {
                                signContract.F_State = 0;
                                signContract.F_StartDate = demandOrder.F_ActivityStartDate;
                                signContract.F_EndDate = demandOrder.F_ActivityEndDate;

                                signContract.Modify(signContract.F_Id);
                                db.Update<ClientOrdersigncontractEntity>(signContract);
                            });

                        }
                        else
                        {
                            var reserves = reserveService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == input.No && p.F_State == 1).ToList();
                            reserves.ForEach(reserve =>
                            {
                                var entity = new ClientOrdersigncontractEntity()
                                {
                                    F_No = input.No,
                                    F_OrderId = keyValue,
                                    F_SiteId = reserve.F_SiteId,
                                    F_SpaceId = reserve.F_SpaceId,
                                    F_StartDate = demandOrder.F_ActivityStartDate,
                                    F_EndDate = demandOrder.F_ActivityEndDate,
                                    F_State = 0
                                };
                                entity.Create();
                                db.Insert<ClientOrdersigncontractEntity>(entity);
                            });
                        }

                        var orderEntity = db.FindEntity<ClientOrderEntity>(keyValue);
                        //orderEntity.F_OrderState = 7;
                        orderEntity.F_OrderStateProcess = 0;// 1;
                        orderEntity.Modify(keyValue);
                        db.Update<ClientOrderEntity>(orderEntity);
                    }
                    db.Commit();
                }
            }

            return result;
        }

        //public void SubmitStopContractForm(OrderSitesFlowInput input, string keyValue)
        //{
        //    var demandOrder = GetDemandOrderByOrderId(input.OrderId);
        //    if (demandOrder != null)
        //    {
        //        using (var db = new RepositoryBase().BeginTrans())
        //        {
        //            input.SiteIds.ForEach(siteAndSpaceId =>
        //            {
        //                var siteId = siteAndSpaceId.Split('|')[0];
        //                var spaceId = siteAndSpaceId.Split('|')[1];

        //                var entity = new ClientOrdersigncontractEntity
        //                {
        //                    F_OrderId = keyValue,
        //                    F_SiteId = siteId,
        //                    F_SpaceId = spaceId,
        //                    F_StartDate = demandOrder.F_ActivityStartDate,
        //                    F_EndDate = demandOrder.F_ActivityEndDate,
        //                    F_State = 0
        //                };
        //                entity.Create();

        //                db.Insert<ClientOrdersigncontractEntity>(entity);
        //            });

        //            var orderEntity = db.FindEntity<ClientOrderEntity>(keyValue);
        //            orderEntity.F_OrderState = 8;
        //            orderEntity.F_OrderStateProcess = 2;
        //            orderEntity.Modify(keyValue);
        //            db.Update<ClientOrderEntity>(orderEntity);

        //            db.Commit();
        //        }
        //    }
        //}

        /// <summary>
        /// 踢单和关闭订单
        /// （可以踢单或关闭订单一次，第二次直接更改了删除状态）
        /// </summary>
        public void SignOutClientOrder(ClientOrderchangerecordEntity entity, string keyValue)
        {
            var currentUser = OperatorProvider.Provider.GetCurrent();

            using (var db = new RepositoryBase().BeginTrans())
            {
                // 1. 更新订单状态
                var orderEntity = service.FindEntity(keyValue);
                if (!orderEntity.IsEmpty())
                {
                    // 更新订单为踢单或关闭状态
                    if (!orderEntity.F_SignOut.HasValue)
                    {
                        orderEntity.F_OrderState = 9;
                        orderEntity.F_OrderStateProcess = -1;
                        orderEntity.F_SignOut = true;       // 表示已经踢单或关闭过订单
                        orderEntity.F_OrderEnvironment = 3; // 更新为公海状态
                        orderEntity.F_FlowUserId = null;
                        orderEntity.Modify(keyValue);

                        db.Update<ClientOrderEntity>(orderEntity);

                        entity.F_FromUserId = currentUser.UserId;
                        entity.F_ToUserId = "";
                        entity.Create();
                        db.Insert<ClientOrderchangerecordEntity>(entity);
                    }
                    else
                    {
                        // 更新为关闭订单状态 多次踢单之后
                        orderEntity.F_State = 0;    // 状态为无效订单

                        orderEntity.Modify(keyValue);
                        db.Update<ClientOrderEntity>(orderEntity);
                    }


                    // 2.更新记录表状态为无效
                    var recomends = db.IQueryable<ClientOrderrecommendEntity>(p => p.F_OrderId == keyValue).ToList();
                    var takelooks = db.IQueryable<ClientOrdertakelookEntity>(p => p.F_OrderId == keyValue).ToList();
                    var takelookdetails = db.IQueryable<ClientOrdertakelookDetailEntity>(p => p.F_OrderId == keyValue).ToList();
                    var takelookallots = db.IQueryable<ClientOrdertakelookallotEntity>(p => p.F_OrderId == keyValue).ToList();
                    var intentions = db.IQueryable<ClientOrderintentionEntity>(p => p.F_OrderId == keyValue).ToList();
                    var intentiondetails = db.IQueryable<ClientOrderintentiondetailEntity>(p => p.F_OrderId == keyValue).ToList();
                    var pricetalks = db.IQueryable<ClientOrderpricetalksEntity>(p => p.F_OrderId == keyValue).ToList();
                    var pricedetails = db.IQueryable<ClientOrderPriceDetailEntity>(p => p.F_OrderId == keyValue).ToList();
                    var reserves = db.IQueryable<ClientOrderreserveEntity>(p => p.F_OrderId == keyValue).ToList();
                    var usings = db.IQueryable<ClientOrderusingEntity>(p => p.F_OrderId == keyValue).ToList();
                    var usingprices = db.IQueryable<ClientOrderusingpriceEntity>(p => p.F_OrderId == keyValue).ToList();
                    var signcontracts = db.IQueryable<ClientOrdersigncontractEntity>(p => p.F_OrderId == keyValue).ToList();

                    var records = db.IQueryable<CheckRecordEntity>(p => p.F_OrderId == keyValue).ToList();

                    recomends.ForEach(item => { item.Remove(); db.Delete<ClientOrderrecommendEntity>(item); });
                    takelooks.ForEach(item => { item.Remove(); db.Delete<ClientOrdertakelookEntity>(item); });
                    takelookdetails.ForEach(item => { item.Remove(); db.Delete<ClientOrdertakelookDetailEntity>(item); });
                    takelookallots.ForEach(item => { item.Remove(); db.Delete<ClientOrdertakelookallotEntity>(item); });
                    intentions.ForEach(item => { item.Remove(); db.Delete<ClientOrderintentionEntity>(item); });
                    intentiondetails.ForEach(item => { item.Remove(); db.Delete<ClientOrderintentiondetailEntity>(item); });
                    pricetalks.ForEach(item => { item.Remove(); db.Delete<ClientOrderpricetalksEntity>(item); });
                    pricedetails.ForEach(item => { item.Remove(); db.Delete<ClientOrderPriceDetailEntity>(item); });
                    reserves.ForEach(item => { item.Remove(); db.Delete<ClientOrderreserveEntity>(item); });
                    usings.ForEach(item => { item.Remove(); db.Delete<ClientOrderusingEntity>(item); });
                    usingprices.ForEach(item => { item.Remove(); db.Delete<ClientOrderusingpriceEntity>(item); });
                    signcontracts.ForEach(item => { item.Remove(); db.Delete<ClientOrdersigncontractEntity>(item); });
                    records.ForEach(item => { item.Remove(); db.Delete<CheckRecordEntity>(item); });

                    db.Commit();
                }
                else
                {
                    this.Log.Error($"未找到客户需求订单： { keyValue }");
                }
            }
        }

        public void SignInClientOrder(string keyValue)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            var orderEntity = service.FindEntity(keyValue);

            orderEntity.F_OrderState = 1;
            orderEntity.F_FlowUserId = LoginInfo.UserId;
            orderEntity.F_IsCheck = 0;
            orderEntity.F_OrderStateProcess = -1;
            orderEntity.F_OrderEnvironment = 1; // 更新为接单状态
            orderEntity.Modify(keyValue);

            service.Update(orderEntity);
        }



        public bool IntentionSite(OrderSitesFlowInput intentionEntity, string keyValue)
        {
            var result = false;
            var orderId = intentionEntity.OrderId;
            IEnumerable<string> siteAndSpaceIds = intentionEntity.SiteIds;
            var demandOrder = GetDemandOrderByOrderId(orderId);
            if (demandOrder != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var sqlStr = $@"SELECT * FROM Site_Client_OrderIntention WHERE F_OrderId='{ keyValue }' AND F_No='{ intentionEntity.No }'";
                    var existIntentions = db.FindList<ClientOrderintentionEntity>(sqlStr);
                    if (existIntentions.Any())
                    {
                        var existIds = existIntentions.Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }|{ p.F_No }");
                        siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                    }
                    // 相关推荐场地没有已推荐过的场地
                    result = intentionEntity.SiteIds.Count == siteAndSpaceIds.Count();

                    if (result)
                    {
                        var takelooks = takelookService.IQueryable(p => p.F_OrderId == keyValue && p.F_No == intentionEntity.No && p.F_State == 1).ToList();
                        if (takelooks.Any())
                        {
                            takelooks.ForEach(takelook =>
                            {
                                // 添加意向场地
                                var iEntity = new ClientOrderintentionEntity
                                {
                                    F_No = takelook.F_No,
                                    F_OrderId = intentionEntity.OrderId,
                                    F_SiteId = takelook.F_SiteId,
                                    F_SpaceId = takelook.F_SpaceId,
                                    F_State = 0
                                };
                                iEntity.Create();
                                db.Insert<ClientOrderintentionEntity>(iEntity);

                                // 添加场地报价申请记录
                                var entity = new ClientOrderpricetalksEntity
                                {
                                    F_No = takelook.F_No,
                                    F_OrderId = intentionEntity.OrderId,
                                    F_SiteId = takelook.F_SiteId,
                                    F_SpaceId = takelook.F_SpaceId,
                                    F_StartDate = demandOrder.F_ActivityStartDate,
                                    F_EndDate = demandOrder.F_ActivityEndDate,
                                    F_State = 0
                                };
                                entity.Create();
                                db.Insert<ClientOrderpricetalksEntity>(entity);

                            });

                            var orderInfo = db.FindEntity<ClientOrderEntity>(intentionEntity.OrderId);
                            if (orderInfo != null)
                            {
                                orderInfo.F_OrderStateProcess = 0;
                                orderInfo.Modify(intentionEntity.OrderId);

                                db.Update<ClientOrderEntity>(orderInfo);
                            }
                            db.Commit();
                        }
                    }
                }
            }
            return result;
        }

        public Dictionary<string, OrderIntentionSiteOutput> GetTakelookGridByIntentionSiteJson(string orderId)
        {
            var result = new Dictionary<string, OrderIntentionSiteOutput>();
            var sqlStr = $@"SELECT scot.F_Id, 
                                scot.F_OrderId, 
		                        space.F_SiteId, 
                                space.F_Id F_SpaceId, 
                                space.title SpaceName, 
                                scotd.F_SourceType, 
                                scotd.F_Source, 
                                ss.title SiteName, 
                                scpc.F_Contact CustomerName, 
                                scpc.F_Phone CustomerPhone, 
                                sc.F_ClientName CompanyName, 
                                su.F_RealName OrderCustomerName, 
                                scot.F_No,
                                scot.F_CreatorTime
                            FROM Site_Client_Order sco 
                            INNER JOIN Site_Client_OrderTakelook scot ON sco.F_Id = scot.F_OrderId
                            LEFT JOIN Site_Client_OrderTakelookDetail scotd ON sco.F_Id = scotd.F_OrderId AND scot.F_SiteId = scotd.F_SiteId AND scot.F_SpaceId = scotd.F_SpaceId
                            INNER JOIN SL_Site ss ON scot.F_SiteId = ss.F_Id
                            INNER JOIN SL_Space space ON scot.F_SiteId = space.F_SiteId AND scot.F_SpaceId = space.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE scot.F_State = 1 AND scot.F_OrderId ='{ orderId }' ORDER BY scot.F_No";
            using (var db = new RepositoryBase())
            {
                var data = db.FindList<OrderIntentionSiteDto>(sqlStr);
                // 去重
                data.ForEach(item =>
                {
                    var key = $"{ item.F_SiteId }|{ item.F_SpaceId }";
                    if (result.ContainsKey(key))
                    {
                        var current = result[key];
                        if (item.F_SourceType == 1)
                        {
                            result[key].Times += (string.IsNullOrEmpty(current.Times) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 2)
                        {
                            result[key].Cars += (string.IsNullOrEmpty(current.Cars) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 3)
                        {
                            result[key].Users += (string.IsNullOrEmpty(current.Users) ? "" : ",") + item.F_Source;
                        }
                    }
                    else
                    {
                        result.Add(key, new OrderIntentionSiteOutput
                        {
                            F_Id = item.F_Id,
                            F_OrderId = item.F_OrderId,
                            F_SiteId = item.F_SiteId,
                            F_SpaceId = item.F_SpaceId,
                            Times = item.F_SourceType == 1 ? item.F_Source : "",
                            Cars = item.F_SourceType == 2 ? item.F_Source : "",
                            Users = item.F_SourceType == 3 ? item.F_Source : "",
                            SiteName = item.SiteName,
                            SpaceName = item.SpaceName,
                            OrderCustomerName = item.OrderCustomerName,
                            CompanyName = item.CompanyName,
                            CustomerName = item.CustomerName,
                            CustomerPhone = item.CustomerPhone,
                            F_No = item.F_No,
                            F_CreatorTime = item.F_CreatorTime
                        });
                    }
                });
                // 格式化JSON Object
                foreach (var item in result)
                {
                    item.Value.Times = string.Format("[{0}]", item.Value.Times);
                    item.Value.Cars = string.Format("[{0}]", item.Value.Cars);
                    item.Value.Users = string.Format("[{0}]", item.Value.Users);
                }

            }
            return result;
        }

        public Dictionary<string, OrderPriceTalksOutput> GetIntentionSiteGridByPriceTalksJson(string orderId)
        {
            var result = new Dictionary<string, OrderPriceTalksOutput>();
            var sqlStr = $@"SELECT  sco.F_Id, 
	                                scopt.F_Id F_PriceTalksId, 
	                                scopt.F_MarketPrice, 
	                                scoid.F_ServiceName, 
	                                scoi.F_OrderId, 
                                    scoi.F_No, 
	                                space.F_SiteId, 
	                                space.F_Id F_SpaceId, 
	                                space.title SpaceName, 
	                                scotd.F_SourceType, 
	                                scotd.F_Source, 
	                                ss.title SiteName, 
	                                scpc.F_Contact CustomerName, 
	                                scpc.F_Phone CustomerPhone, 
	                                sc.F_ClientName CompanyName, 
	                                su.F_RealName OrderCustomerName, 
	                                scopt.F_CreatorTime
                            FROM Site_Client_Order sco 
                            INNER JOIN Site_Client_OrderIntention scoi ON sco.F_Id = scoi.F_OrderId
                            LEFT JOIN Site_Client_OrderIntentionDetail scoid ON sco.F_Id = scoid.F_OrderId AND scoi.F_SiteId = scoid.F_SiteId AND scoi.F_SpaceId = scoid.F_SpaceId
                            LEFT JOIN Site_Client_OrderTakelook scot ON sco.F_Id = scot.F_OrderId AND scoi.F_SiteId = scot.F_SiteId AND scoi.F_SpaceId = scot.F_SpaceId
                            LEFT JOIN Site_Client_OrderTakelookDetail scotd ON sco.F_Id = scotd.F_OrderId AND scoi.F_SiteId = scotd.F_SiteId AND scoi.F_SpaceId = scotd.F_SpaceId  AND scotd.F_SourceType = 1
                            LEFT JOIN Site_Client_OrderPriceTalks scopt ON sco.F_Id = scopt.F_OrderId AND scoi.F_SiteId = scopt.F_SiteId AND scoi.F_SpaceId = scopt.F_SpaceId
                            INNER JOIN SL_Site ss ON scoi.F_SiteId = ss.F_Id
                            INNER JOIN SL_Space space ON scoi.F_SiteId = space.F_SiteId AND scoi.F_SpaceId = space.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE  sco.F_Id ='{ orderId }' ORDER BY scoi.F_No";
            using (var db = new RepositoryBase())
            {
                var data = db.FindList<OrderPriceTalksDto>(sqlStr);
                // 去重
                data.ForEach(item =>
                {
                    var key = $@"{item.F_OrderId}|{item.F_SiteId}|{item.F_SpaceId}|{item.F_No}";
                    if (result.ContainsKey(key))
                    {
                        var current = result[key];
                        if (item.F_SourceType == 1)
                        {
                            if (result[key].Times.IndexOf(current.Times) == -1)
                            {
                                result[key].Times += (string.IsNullOrEmpty(current.Times) ? "" : ",") + item.F_Source;
                            }
                        }
                        result[key].F_ServiceName += (string.IsNullOrEmpty(current.F_ServiceName) ? "" : ",") + string.Concat("\"", item.F_ServiceName, "\"");
                    }
                    else
                    {
                        result.Add(key, new OrderPriceTalksOutput
                        {
                            F_Id = item.F_Id,
                            F_PriceTalksId = item.F_PriceTalksId,
                            F_MarketPrice = item.F_MarketPrice,
                            F_OrderId = item.F_OrderId,
                            F_SiteId = item.F_SiteId,
                            F_SpaceId = item.F_SpaceId,
                            Times = item.F_SourceType == 1 ? item.F_Source : "",
                            F_ServiceName = string.Concat("\"", item.F_ServiceName, "\""),
                            SiteName = item.SiteName,
                            SpaceName = item.SpaceName,
                            OrderCustomerName = item.OrderCustomerName,
                            CompanyName = item.CompanyName,
                            CustomerName = item.CustomerName,
                            CustomerPhone = item.CustomerPhone,
                            F_No = item.F_No,
                            F_CreatorTime = item.F_CreatorTime
                        });
                    }
                });
                // 格式化JSON Object
                foreach (var item in result)
                {
                    item.Value.Times = string.Format("[{0}]", item.Value.Times);
                    item.Value.F_ServiceName = string.Format("[{0}]", item.Value.F_ServiceName);
                }

            }
            return result;
        }

        public List<OrderReserveSiteOutput> GetPriceTalksGridByReserveSiteJson(string orderId)
        {
            var sqlStr = $@"SELECT  scopt.F_Id, 
	                                scopt.F_OrderId, 
                                    scopt.F_No,
	                                scopt.F_SiteId, 
	                                scopt.F_SpaceId,
	                                space.title SpaceName,
	                                ss.title SiteName, 
	                                scpc.F_Contact CustomerName, 
	                                scpc.F_Phone CustomerPhone, 
	                                sc.F_ClientName CompanyName, 
	                                su.F_RealName OrderCustomerName, 
                                    scor.F_State,
	                                scor.F_ReserveTime, 
	                                scor.F_CreatorTime
	                            FROM Site_Client_Order sco 
	                            INNER JOIN Site_Client_OrderPriceTalks scopt ON sco.F_Id = scopt.F_OrderId
	                            LEFT JOIN Site_Client_OrderReserve scor ON sco.F_Id = scor.F_OrderId AND scopt.F_SiteId = scor.F_SiteId AND scopt.F_SpaceId = scor.F_SpaceId
	                            INNER JOIN SL_Site ss ON scopt.F_SiteId = ss.F_Id
	                            INNER JOIN SL_Space space ON scopt.F_SiteId = space.F_SiteId AND scopt.F_SpaceId = space.F_Id
	                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
	                            LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
	                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
	                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
	                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE (scopt.F_State is null or scopt.F_State in(0,1)) AND scopt.F_OrderId = '{ orderId }' ORDER BY scopt.F_No";
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<OrderReserveSiteOutput>(sqlStr);

                return result;
            }

        }

        public List<OrderSignContractOutput> GetReserveSiteGridBySignContractJson(string orderId)
        {
            var sqlStr = $@"SELECT scor.F_Id, 
                                   scor.F_OrderId, 
                                   scor.F_SiteId, 
                                   scor.F_SpaceId,
                                   scor.F_No,
                                   space.title SpaceName,
                                   ss.title SiteName, 
                                   scpc.F_Contact CustomerName, 
                                   scpc.F_Phone CustomerPhone, 
                                   sc.F_ClientName CompanyName, 
                                   su.F_RealName OrderCustomerName, 
                                   scor.F_ReserveTime,
                                   scosc.F_FilePath,
                                   scosc.F_FileName,
                                   scosc.F_CreatorTime,
                                   scosc.F_State
                              FROM Site_Client_Order sco 
                              INNER JOIN Site_Client_OrderReserve scor ON sco.F_Id = scor.F_OrderId
                              LEFT JOIN Site_Client_OrderSignContract scosc ON sco.F_Id = scosc.F_OrderId AND scor.F_SiteId = scosc.F_SiteId AND scor.F_SpaceId = scosc.F_SpaceId
                              INNER JOIN SL_Site ss ON scor.F_SiteId = ss.F_Id
                              INNER JOIN SL_Space space ON scor.F_SiteId = space.F_SiteId AND scor.F_SpaceId = space.F_Id
                              LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                              LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                              LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                              LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                              LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE scor.F_State=1 AND scor.F_OrderId ='{ orderId }' ORDER BY scor.F_No";
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<OrderSignContractOutput>(sqlStr);
                return result;
            }

        }

        public void DeleteIntentionDetailForm(string keyValue)
        {
            intentionDetailService.Delete(p => p.F_Id == keyValue);
        }

        public List<OrderIntentionDetailOutput> IntentionDetail(string orderId)
        {
            var sqlStr = $@"SELECT  scot.F_Id, 
		                            scot.F_OrderId, 
		                            space.F_SiteId, 
                                    space.F_Id F_SpaceId, 
                                    space.title SpaceName, 
		                            scot.F_ServiceCode, 
		                            scot.F_ServiceName, 
		                            scot.F_Num, 
                                    scot.F_Price, 
		                            units.F_PriceUnit, 
		                            ss.title SiteName, 
		                            scot.F_Remark
                            FROM Site_Client_OrderIntentionDetail scot 
                            INNER JOIN SL_Site ss ON scot.F_SiteId = ss.F_Id
                            INNER JOIN SL_Space space ON scot.F_SiteId = space.F_SiteId AND scot.F_SpaceId = space.F_Id
                            LEFT JOIN (select sid.F_ItemCode as 'F_PriceUnitCode', sid.F_ItemName as 'F_PriceUnit' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='units') units ON scot.F_PriceUnit = units.F_PriceUnitCode
                            WHERE F_OrderId ='{ orderId }' ORDER BY scot.F_SiteId, scot.F_SpaceId";
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<OrderIntentionDetailOutput>(sqlStr);
                return result;
            }
        }

        public List<OrderTakelookDetailOutput> TakelookDetail(string orderId)
        {
            var sqlStr = $@"SELECT scot.F_Id, 
		                           scot.F_OrderId, 
		                           space.F_SiteId, 
                                   space.F_Id F_SpaceId, 
                                   space.title SpaceName, 
		                           scot.F_SourceType, 
		                           scot.F_Source, 
		                           ss.title SiteName 
                            FROM Site_Client_OrderTakelookDetail scot 
                            INNER JOIN SL_Site ss ON scot.F_SiteId = ss.F_Id
                            INNER JOIN SL_Space space ON scot.F_SiteId = space.F_SiteId AND scot.F_SpaceId = space.F_Id
                            WHERE F_OrderId ='{ orderId }'";
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<OrderTakelookDetailOutput>(sqlStr);
                return result;
            }
        }

        public Dictionary<string, OrderTakelookOutput> GetRecommendByTakelookList(string orderId)
        {
            var result = new Dictionary<string, OrderTakelookOutput>();
            var sqlStr = $@"SELECT   scor.F_Id, 
                                     sco.F_WorkFormId,
                                     scor.F_OrderId, 
                                     scor.F_No,
                                     space.F_SiteId, 
                                     space.F_Id F_SpaceId, 
                                     space.title SpaceName, 
                                     scotd.F_SourceType, 
                                     scotd.F_Source, 
                                     ss.title SiteName, 
                                     scor.F_State, 
                                     scpc.F_Contact CustomerName, 
                                     scpc.F_Phone CustomerPhone, 
                                     sc.F_ClientName CompanyName, 
                                     su.F_RealName OrderCustomerName
                              FROM Site_Client_Order sco 
                              LEFT JOIN Site_Client_OrderRecommend scor ON sco.F_Id = scor.F_OrderId
                              LEFT JOIN Site_Client_OrderTakelookDetail scotd ON scor.F_OrderId = scotd.F_OrderId AND scor.F_SiteId = scotd.F_SiteId AND scor.F_SpaceId = scotd.F_SpaceId
                              INNER JOIN SL_Site ss ON scor.F_SiteId = ss.F_Id
                              INNER JOIN SL_Space space ON scor.F_SiteId = space.F_SiteId AND scor.F_SpaceId = space.F_Id
                              LEFT JOIN Site_Client_OrderTakelook scot ON scor.F_OrderId = scot.F_OrderId AND scor.F_SiteId = scot.F_SiteId AND scor.F_SpaceId = scot.F_SpaceId
                              LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                              LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                              LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                              LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                              LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE scor.F_State=1 AND scor.F_OrderId ='{ orderId }' ORDER BY scor.F_No,scor.F_State";
            using (var db = new RepositoryBase())
            {
                var data = db.FindList<OrdertakelookDto>(sqlStr);
                // 去重
                data.ForEach(item =>
                {
                    var key = $@"{item.F_SiteId}|{item.F_SpaceId}";
                    if (result.ContainsKey(key))
                    {
                        var current = result[key];
                        if (item.F_SourceType == 1)
                        {
                            result[key].Times += (string.IsNullOrEmpty(current.Times) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 2)
                        {
                            result[key].Cars += (string.IsNullOrEmpty(current.Cars) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 3)
                        {
                            result[key].Users += (string.IsNullOrEmpty(current.Users) ? "" : ",") + item.F_Source;
                        }
                    }
                    else
                    {
                        result.Add(key, new OrderTakelookOutput
                        {
                            F_Id = item.F_Id,
                            F_OrderId = item.F_OrderId,
                            F_SiteId = item.F_SiteId,
                            F_SpaceId = item.F_SpaceId,
                            Times = item.F_SourceType == 1 ? item.F_Source : "",
                            Cars = item.F_SourceType == 2 ? item.F_Source : "",
                            Users = item.F_SourceType == 3 ? item.F_Source : "",
                            SiteName = item.SiteName,
                            SpaceName = item.SpaceName,
                            OrderCustomerName = item.OrderCustomerName,
                            CompanyName = item.CompanyName,
                            CustomerName = item.CustomerName,
                            CustomerPhone = item.CustomerPhone,
                            F_No = item.F_No,
                            F_State = item.F_State
                        });
                    }
                });
                // 格式化JSON Object
                foreach (var item in result)
                {
                    item.Value.Times = string.Format("[{0}]", item.Value.Times);
                    item.Value.Cars = string.Format("[{0}]", item.Value.Cars);
                    item.Value.Users = string.Format("[{0}]", item.Value.Users);
                }

            }
            return result;
        }

        /// <summary>
        /// 获取带看反馈记录
        /// </summary>
        public Dictionary<string, OrderTakelookOutput> GetRecommendByTakelookFeelbackList(string orderId)
        {
            var result = new Dictionary<string, OrderTakelookOutput>();
            var sqlStr = $@"SELECT scot.F_Id, 
                                   sco.F_WorkFormId,
                                   scot.F_OrderId, 
                                   scot.F_No,
                                   space.F_SiteId, 
                                   space.F_Id F_SpaceId, 
                                   space.title SpaceName, 
                                   scotd.F_SourceType, 
                                   scotd.F_Source, 
                                   ss.title SiteName, 
                                   scot.F_State, 
                                   scpc.F_Contact CustomerName, 
                                   scpc.F_Phone CustomerPhone, 
                                   sc.F_ClientName CompanyName, 
                                   su.F_RealName OrderCustomerName
                            FROM Site_Client_Order sco 
                            LEFT JOIN Site_Client_OrderTakelook scot ON sco.F_Id = scot.F_OrderId
                            LEFT JOIN Site_Client_OrderTakelookDetail scotd ON scot.F_OrderId = scotd.F_OrderId AND scot.F_SiteId = scotd.F_SiteId AND scot.F_SpaceId = scotd.F_SpaceId
                            INNER JOIN SL_Site ss ON scot.F_SiteId = ss.F_Id
                            INNER JOIN SL_Space space ON scot.F_SiteId = space.F_SiteId AND scot.F_SpaceId = space.F_Id
                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                            LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                            WHERE scot.F_OrderId ='{ orderId }' ORDER BY scot.F_No,scot.F_State";
            using (var db = new RepositoryBase())
            {
                var data = db.FindList<OrdertakelookDto>(sqlStr);
                // 去重
                data.ForEach(item =>
                {
                    var key = $@"{item.F_SiteId}|{item.F_SpaceId}";
                    if (result.ContainsKey(key))
                    {
                        var current = result[key];
                        if (item.F_SourceType == 1)
                        {
                            result[key].Times += (string.IsNullOrEmpty(current.Times) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 2)
                        {
                            result[key].Cars += (string.IsNullOrEmpty(current.Cars) ? "" : ",") + item.F_Source;
                        }
                        else if (item.F_SourceType == 3)
                        {
                            result[key].Users += (string.IsNullOrEmpty(current.Users) ? "" : ",") + item.F_Source;
                        }
                    }
                    else
                    {
                        result.Add(key, new OrderTakelookOutput
                        {
                            F_Id = item.F_Id,
                            F_OrderId = item.F_OrderId,
                            F_SiteId = item.F_SiteId,
                            F_SpaceId = item.F_SpaceId,
                            Times = item.F_SourceType == 1 ? item.F_Source : "",
                            Cars = item.F_SourceType == 2 ? item.F_Source : "",
                            Users = item.F_SourceType == 3 ? item.F_Source : "",
                            SiteName = item.SiteName,
                            SpaceName = item.SpaceName,
                            OrderCustomerName = item.OrderCustomerName,
                            CompanyName = item.CompanyName,
                            CustomerName = item.CustomerName,
                            CustomerPhone = item.CustomerPhone,
                            F_No = item.F_No,
                            F_State = item.F_State
                        });
                    }
                });
                // 格式化JSON Object
                foreach (var item in result)
                {
                    item.Value.Times = string.Format("[{0}]", item.Value.Times);
                    item.Value.Cars = string.Format("[{0}]", item.Value.Cars);
                    item.Value.Users = string.Format("[{0}]", item.Value.Users);
                }

            }
            return result;
        }

        /// <summary>
        /// 推荐场地
        /// </summary>
        public bool SendSite(string randomNo, OrderSitesFlowInput rInput)
        {
            var result = false;
            var orderId = rInput.OrderId;
            IEnumerable<string> siteAndSpaceIds = rInput.SiteIds;
            var demandOrder = GetDemandOrderByOrderId(orderId);
            if (demandOrder != null)
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    // 判断此订单是否有相关的场地推荐内容
                    var sqlStr = $@"SELECT * FROM Site_Client_OrderRecommend WHERE F_OrderId='{ orderId }'";
                    var existSites = db.FindList<ClientOrderrecommendEntity>(sqlStr);
                    if (existSites.Any())
                    {
                        var existIds = existSites.Select(p => $"{ p.F_SiteId }|{ p.F_SpaceId }");
                        siteAndSpaceIds = siteAndSpaceIds.Except(existIds);
                    }
                    // 相关推荐场地没有已推荐过的场地
                    result = rInput.SiteIds.Count == siteAndSpaceIds.Count();
                    if (result)
                    {
                        // 添加未推荐过的场地
                        foreach (var siteAndSpaceId in siteAndSpaceIds)
                        {
                            var siteId = siteAndSpaceId.Split('|')[0];
                            var spaceId = siteAndSpaceId.Split('|')[1];
                            var orEntity = new ClientOrderrecommendEntity
                            {
                                F_No = randomNo,
                                F_OrderId = rInput.OrderId,
                                F_SiteId = siteId,
                                F_SpaceId = spaceId,
                                F_StartDate = demandOrder.F_ActivityStartDate,
                                F_EndDate = demandOrder.F_ActivityEndDate,
                                F_State = 0
                            };
                            orEntity.Create();
                            db.Insert<ClientOrderrecommendEntity>(orEntity);
                        }

                        var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                        if (orderInfo != null)
                        {
                            // 更新订单状态为 0:等待确认
                            orderInfo.F_OrderStateProcess = 0;
                            orderInfo.Modify(rInput.OrderId);

                            db.Update<ClientOrderEntity>(orderInfo);
                        }
                        db.Commit();
                    }
                }
            }
            return result;
        }

        public List<OrderRecommendOutput> GetSendSiteGridByTakelookJson(string orderId)
        {
            var sqlStr = @"SELECT scor.F_OrderId, 
                                 scor.F_No, 
		                         space.F_SiteId, 
 		                         space.F_Id F_SpaceId, 
 		                         space.title SpaceName, 
		                         scpc.F_Contact CustomerName, 
		                         scpc.F_Phone CustomerPhone, 
		                         sc.F_ClientName CompanyName, 
		                         sco.F_FlowUserId, 
		                         ss.title SiteName, 
		                         su.F_RealName LookUserName, 
		                         scor.F_CreatorTime
                        FROM Site_Client_OrderRecommend scor
                        LEFT JOIN Site_Client_Order sco ON scor.F_OrderId = sco.F_Id
                        LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                        LEFT JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                        LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                        LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                        LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                        INNER JOIN SL_Site ss ON scor.F_SiteId = ss.F_Id
                        INNER JOIN SL_Space space ON scor.F_SiteId = space.F_SiteId AND scor.F_SpaceId = space.F_Id
	                    WHERE scor.F_State = 1 AND scor.F_OrderId=@orderId ORDER BY scor.F_No";

            using (var db = new RepositoryBase())
            {
                var dbParams = new MySqlParameter[] {
                    new MySqlParameter("@orderId", orderId)
                };
                var result = db.FindList<OrderRecommendOutput>(sqlStr, dbParams);
                return result;
            }
        }

        public List<SelectListItemViewModel> GetItemList(string enCode)
        {
            var sqlStr = @"SELECT sid.F_ItemCode Value, sid.F_ItemName Text,sid.F_Description FROM Sys_Items si
	                            LEFT JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
	                            WHERE si.F_EnCode=@enCode order by sid.F_SortCode";

            var dbParams = new MySqlParameter[] {
                new MySqlParameter("@enCode", enCode)
            };
            using (var db = new RepositoryBase())
            {
                var result = db.FindList<SelectListItemViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        public ClientOrderEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(ClientOrderEntity clientOrderEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                clientOrderEntity.Modify(keyValue);
                service.Update(clientOrderEntity);
            }
            else
            {
                clientOrderEntity.Create();
                // clientOrderEntity.F_Category = 2;
                service.Insert(clientOrderEntity);
            }
        }

        public void SubmitIntentionForm(List<IntentionDetailDto> list, string keyValue)
        {
            list.ForEach(item =>
            {
                if (item.F_SiteAndSpaceId.Contains('|'))
                {
                    var siteId = item.F_SiteAndSpaceId.Split('|')[0];
                    var spaceId = item.F_SiteAndSpaceId.Split('|')[1];

                    var entity = new ClientOrderintentiondetailEntity
                    {
                        F_OrderId = item.F_OrderId,
                        F_ServiceCode = item.F_ServiceCode,
                        F_ServiceName = item.F_ServiceName,
                        F_Num = item.F_Num,
                        F_PriceUnit = item.F_PriceUnit,
                        F_Remark = item.F_Remark
                    };
                    entity.F_SiteId = siteId;
                    entity.F_SpaceId = spaceId;
                    entity.Create();
                    intentionDetailService.Insert(entity);
                }
            });

        }

        public void SubmitPriceTalksForm(ClientOrderPriceDetailEntity entity, string keyValue)
        {
            var dbEntity = GetPriceDetail(entity.F_OrderId, entity.F_SiteId, entity.F_SpaceId);
            if (dbEntity != null)
            {
                dbEntity.F_MarketPrice = entity.F_MarketPrice;
                dbEntity.F_YunPrice = entity.F_YunPrice;
                dbEntity.F_TotalPrice = entity.F_TotalPrice;
                dbEntity.F_Quantity = entity.F_Quantity;
                dbEntity.F_SpaceArea = entity.F_SpaceArea;
                dbEntity.F_Unit = entity.F_Unit;

                dbEntity.Modify(dbEntity.F_Id);

                priceDetailService.Update(dbEntity);
            }
        }

        /// <summary>
        /// 获取报价单明细
        /// </summary>
        public ClientOrderPriceDetailEntity GetPriceDetail(string orderId, string siteId, string spaceId)
        {
            var entity = priceDetailService.FindEntity(p => p.F_OrderId == orderId && p.F_SiteId == siteId && p.F_SpaceId == spaceId);
            return entity;
        }



        public List<DeptByUserViewModel> GetDeptByUsers()
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            RoleApp role = new RoleApp();
            RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
            string F_GroupId = "";
            if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
            {
                F_GroupId += " and sy.F_GroupId='" + LoginInfo.F_GroupId + "'";
            }
            else if (roleEntity.F_EnCode == "1004")
            {
                F_GroupId += " and sy.F_GroupId='" + LoginInfo.F_GroupId + "' and sy.F_Id='" + LoginInfo.F_GroupId + "'";
            }
            else if (roleEntity.F_EnCode == "1005")
            {
                F_GroupId += " and so.F_Encode in ('MarketingCenter','BEIJINGFB') ";
            }

            var sqlStr = $@"SELECT sy.F_Id as 'F_UserId', sy.F_RealName as 'F_UserName', sy.F_DepartmentId as 'F_OrganizeId', so.F_FullName as 'F_OrganizeName' 
		                    FROM Sys_Organize so
		                    INNER JOIN Sys_User sy ON so.F_Id = sy.F_DepartmentId
		                     where 1=1 " + F_GroupId + " order by sy.F_DepartmentId desc";

            using (var db = new RepositoryBase())
            {
                var result = db.FindList<DeptByUserViewModel>(sqlStr);
                return result;
            }
        }

        public List<DeptByUserViewModel> GetDeptByUsersByDeptId(string deptId)
        {
            var LoginInfo = OperatorProvider.Provider.GetCurrent();
            RoleApp role = new RoleApp();
            RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
            string F_GroupId = "";
            if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
            {
                F_GroupId += " and sy.F_GroupId='" + LoginInfo.F_GroupId + "'";
            }
            else if (roleEntity.F_EnCode == "1004")
            {
                F_GroupId += " and sy.F_GroupId='" + LoginInfo.F_GroupId + "' and sy.F_Id='" + LoginInfo.F_GroupId + "'";
            }
            else if (roleEntity.F_EnCode == "1005")
            {
                F_GroupId += " and so.F_Encode in ('MarketingCenter','BEIJINGFB') ";
            }

            var sqlStr = $@"SELECT sy.F_Id as 'F_UserId', sy.F_RealName as 'F_UserName', sy.F_DepartmentId as 'F_OrganizeId', so.F_FullName as 'F_OrganizeName' 
		                    FROM Sys_Organize so
		                    INNER JOIN Sys_User sy ON so.F_Id = sy.F_DepartmentId
		                     where 1=1 and sy.F_DepartmentId in ('" + deptId + "') " + F_GroupId + " order by sy.F_DepartmentId desc";
            List<DeptByUserViewModel> result = new List<DeptByUserViewModel>();
            using (var db = new RepositoryBase())
            {
                result = db.FindList<DeptByUserViewModel>(sqlStr);
            }
            return result;
        }

        public bool SubmitDeptByUsers(DeptByUserViewModel deptByUserViewModel, string keyValue)
        {
            var result = false;
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var db = new RepositoryBase().BeginTrans())
            {
                var clientOrder = GetForm(keyValue);
                if (!clientOrder.F_SignOut.HasValue || !clientOrder.F_SignOut.Value)
                {
                    result = true;

                    clientOrder.F_OldFlowUserId = clientOrder.F_FlowUserId;
                    clientOrder.F_FlowUserId = deptByUserViewModel.F_UserId;
                    clientOrder.F_SignOut = true;

                    clientOrder.Modify(keyValue);
                    db.Update<ClientOrderEntity>(clientOrder);

                    db.Commit();
                }

            }
            return result;
        }

        public bool SubmitOrderDeptByUsers(DeptByUserViewModel deptByUserViewModel, string keyValue)
        {
            var result = false;
            var currentUser = OperatorProvider.Provider.GetCurrent();
            using (var db = new RepositoryBase().BeginTrans())
            {
                var clientOrder = GetForm(keyValue);
                //if (!clientOrder.F_SignOut.HasValue || !clientOrder.F_SignOut.Value)
                //{
                result = true;

                clientOrder.F_OrderState = 1;
                clientOrder.F_OrderStateProcess = -1;
                clientOrder.F_FlowUserId = deptByUserViewModel.F_UserId;
                //clientOrder.F_SignOut = true;

                clientOrder.Modify(keyValue);
                db.Update<ClientOrderEntity>(clientOrder);

                // 相关踢单记录
                var entity = new ClientOrderchangerecordEntity
                {
                    F_OrderId = keyValue,
                    F_ChangeType = 1,
                    F_FromUserId = currentUser.UserId,
                    F_ToUserId = deptByUserViewModel.F_UserId,
                    F_ChangeReason = -1,
                    F_Note = deptByUserViewModel.Remark
                };
                entity.Create();
                db.Insert<ClientOrderchangerecordEntity>(entity);

                db.Commit();
                //}

            }
            return result;
        }

        /// <summary>
        /// 获取订单基本信息
        /// </summary>
        public OrderInfoViewModel GetOrderInfo(string orderId, string isread)
        {
            ClientOrderEntity entity = service.FindEntity(orderId);
            if ((entity.F_IsRead == 0 || entity.F_IsRead == null) && isread == "1")
            {
                entity.F_IsRead = 1;
                entity.Modify(orderId);
                service.Update(entity);
            }
            var sqlStr = @"SELECT  sco.F_Id OrderId, 
                                   scpd.F_Id DemandId,
                                   scpd.F_ClientId ClientId,
                                   scpc.F_Id ContactId,
                                   sca.F_Id ProjectId,
                                   sco.F_WorkFormId, 
                                   sco.F_OrderState, 
                                   sco.F_OrderStateProcess, 
                                   scpd.F_ActivityTheme, 
                                   scpd.F_ActivityType, 
                                   scpd.F_PersionNumber,
                                   scpd.F_ActivityStartDate, 
                                   scpd.F_ActivityEndDate, 
                                   scpd.F_ActivityCityId, 
                                   scpd.F_SiteType, 
                                   scpd.F_SiteArea, 
                                   IFNULL(scpd.F_Height, 0.00) F_Height, 
                                   scpd.F_DemandCash, 
                                   scpd.F_BuildDate,
                                   scpd.F_Note,
                                   sc.F_ClientName, 
                                   sc.F_ClientLevel, 
                                   sc.F_ClientType, 
                                   scpc.F_Contact,
                                   scpc.F_DepartmentId, 
                                   scpc.F_Phone, 
                                   scpc.F_Mail,
                                   scpc.F_PositionId, 
                                   sca.F_ProjectName, 
                                   adept.F_PositionName, 
                                   asite.F_SiteTypeName, 
                                   atype.F_ActivityTypeName,
                                   so.F_DepartmentName, 
                                   client1.F_ClientTypeName,
                                   client2.F_ClientLevelName
                            FROM Site_Client_Order sco 
                            INNER JOIN Site_Clients_ProjectByDemand scpd ON sco.F_DemandId = scpd.F_Id	
                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                            LEFT JOIN Site_Clients sc ON scpd.F_ClientId = sc.F_Id
                            LEFT JOIN Site_Clients_AllProjects sca ON scpc.F_ClientId = sca.F_ClientId  
                            LEFT JOIN (select sid.F_ItemCode as 'F_DepartmentId', sid.F_ItemName as 'F_DepartmentName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='bmmc') so ON scpc.F_DepartmentId = so.F_DepartmentId  
                            LEFT JOIN (select sid.F_ItemCode as 'F_ActivityType', sid.F_ItemName as 'F_ActivityTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='ActivityType') atype ON scpd.F_ActivityType = atype.F_ActivityType
                            LEFT JOIN (select sid.F_ItemCode as 'F_SiteType', sid.F_ItemName as 'F_SiteTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='SiteType') asite ON scpd.F_SiteType = asite.F_SiteType
                            LEFT JOIN (select sid.F_ItemCode as 'F_PositionId', sid.F_ItemName as 'F_PositionName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='gszw') adept ON scpc.F_PositionId = adept.F_PositionId
                            LEFT JOIN (select sid.F_ItemCode as 'F_ClientLevel', sid.F_ItemName as 'F_ClientLevelName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='khdj') client2 ON sc.F_ClientLevel = client2.F_ClientLevel
                            LEFT JOIN (select sid.F_ItemCode as 'F_ClientType', sid.F_ItemName as 'F_ClientTypeName' from Sys_Items si INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId AND si.F_EnCode='khlx') client1 ON sc.F_ClientType = client1.F_ClientType
		                   WHERE sco.F_Id = @orderId";

            using (var db = new RepositoryBase())
            {
                var dbParams = new MySqlParameter[] {
                    new MySqlParameter("@orderId", orderId)
                };

                var result = db.FirstOrDefault<OrderInfoViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        /// <summary>
        /// 关闭订单
        /// </summary>
        /// <param name="orderId"></param>
        public void CloseOrder(string orderId)
        {
            var order = service.FindEntity(orderId);
            order.F_OrderState = 9;
            order.F_OrderEnvironment = 3;
            order.Modify(order.F_Id);
            service.Update(order);
        }

        #region 流程流转


        public List<OrderCheckRecordOutput> GetOrderCheckRecordList(string orderId)
        {
            var sqlStr = @"SELECT    SCR.F_Id,
		                             SCR.F_OrderId,
		                             SCR.F_ApplyType,
		                             SCR.F_CheckContent,
		                             SCR.F_CheckUserId,
		                             SU.F_RealName F_CheckUserName,
		                             SCR.F_State,
		                             SCR.F_CheckTime,
		                             IFNULL(SCR.F_Note, '') F_Note,
		                             SCR.F_CreatorTime
	                            FROM Sys_CheckRecord SCR
	                            LEFT JOIN Sys_User SU ON SCR.F_CheckUserId = SU.F_Id
	                            WHERE SCR.F_OrderId = @orderId";

            using (var db = new RepositoryBase())
            {
                var dbParams = new MySqlParameter[] {
                    new MySqlParameter("@orderId", orderId)
                };
                var result = db.FindList<OrderCheckRecordOutput>(sqlStr, dbParams);
                return result;
            }
        }

        /// <summary>
        /// 客户订单场地推荐表
        /// </summary>
        public List<OrderRecommendViewModel> GetOrderRecommendList(string orderId)
        {
            var sqlStr = @"SELECT scor.F_OrderId, scor.F_No, sy.title F_Title, ss.title F_SpaceTitle, scor.F_CreatorTime, scor.F_Remark, scor.F_State
		                    FROM Site_Client_OrderRecommend scor
		                    INNER JOIN SL_Site sy ON scor.F_SiteId = sy.F_Id
		                    LEFT JOIN SL_Space ss ON sy.F_Id = ss.F_SiteId AND scor.F_SpaceId = ss.F_Id
		                    WHERE scor.F_OrderId =@orderId ORDER BY scor.F_No";

            using (var db = new RepositoryBase())
            {
                var dbParams = new MySqlParameter[] {
                    new MySqlParameter("@orderId", orderId)
                };
                var result = db.FindList<OrderRecommendViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        /// <summary>
        /// 客户场地带看表
        /// </summary>
        public List<OrderTakelookViewModel> GetOrderTakelookList(string orderId)
        {
            var sqlStr = @"SELECT    sy.title F_Title, 
		                             sy.Mocha_ITOM, 
		                             su2.F_RealName Mocha_ITOMName, 
		                             '' F_Source, 
		                             sco.F_FlowUserId, 
		                             su1.F_RealName F_FlowUserName, 
		                             scot.F_CreatorTime, 
		                             scot.F_Remark
                            FROM Site_Client_OrderTakelook scot
                            INNER JOIN SL_Site sy ON scot.F_SiteId = sy.F_Id
                            INNER JOIN Site_Client_Order sco ON scot.F_OrderId = sco.F_Id
                            LEFT JOIN Sys_User su1 ON  sco.F_FlowUserId = su1.F_Id
                            LEFT JOIN Sys_User su2 ON  sy.Mocha_ITOM = su1.F_Id
		                    WHERE scot.F_OrderId = @orderId";

            using (var db = new RepositoryBase())
            {
                var dbParams = new MySqlParameter[] {
                    new MySqlParameter("@orderId", orderId)
                };
                var result = db.FindList<OrderTakelookViewModel>(sqlStr, dbParams);
                return result;
            }
        }

        #endregion

        #region 客服回访记录

        /// <summary>
        /// 获取客服回访记录
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="queryJson"></param>
        /// <param name="type"></param>
        /// <param name="environment"></param>
        /// <returns></returns>
        public List<ClientOrderViewModel> GetReturnVisitList(Pagination pagination, string queryJson, string type, string environment = "3")
        {
            var queryParam = queryJson.ToJObject();
            var currentUser = OperatorProvider.Provider.GetCurrent();

            using (var db = new RepositoryBase())
            {
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                RoleApp role = new RoleApp();
                RoleEntity roleEntity = role.GetForm(LoginInfo.RoleId);
                OrganizeApp organize = new OrganizeApp();
                OrganizeEntity organizeEntity = organize.GetForm(LoginInfo.DepartmentId);

                string F_GroupId = "";
                if (type != "self")
                {
                    if (roleEntity.F_EnCode == "1006" || roleEntity.F_EnCode == "1012")
                    {
                        F_GroupId += " and su.F_GroupId='" + LoginInfo.F_GroupId + "'";
                    }
                    else if (roleEntity.F_EnCode == "1004")
                    {
                        F_GroupId += " and su.F_GroupId='" + LoginInfo.F_GroupId + "' and su.F_Id='" + LoginInfo.F_GroupId + "'";
                    }
                }



                // 订单表(Site_Client_Order)的数据来源于需求表(Site_Clients_ProjectByDemand), 如果不一一配置那就说明数据删除过,不用处理。

                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;

                var extendFilterSql = "";
                var orderSql = $" ORDER BY t.{ pagination.sidx } { pagination.sord } LIMIT { startNo },{ endNo };";
                var extendLastFilterSql = "";

                if (!string.IsNullOrEmpty(type) && type == "self")
                {
                    extendFilterSql += $" AND sco.F_FlowUserId = '{ currentUser.UserId }'";
                }
                if (!queryParam["keyword"].IsEmpty())
                {
                    var keyword = queryParam["keyword"].ToString();
                    extendFilterSql += $" AND scp.F_ActivityTheme LIKE '%{ keyword }%'";
                }

                if (!queryParam["F_Source"].IsEmpty() && queryParam["F_Source"].ToString() != "-1")
                {
                    var sourcetype = queryParam["F_Source"].ToString();
                    extendFilterSql += $" AND scp.F_Source = '{ sourcetype }'";
                }

                if (!queryParam["F_ActivityType"].IsEmpty())
                {
                    string sourcetype = queryParam["F_ActivityType"].ToString();
                    extendFilterSql += $" AND scp.F_ActivityType = '{ sourcetype }'";
                }

                if (!queryParam["F_CreatorDate"].IsEmpty())
                {
                    string creatorDate = queryParam["F_CreatorDate"].ToString();
                    extendLastFilterSql += $" AND t.ReturnVisitedCreatorTime >= '{ creatorDate }'";
                }

                if (!queryParam["F_CreatorDate2"].IsEmpty())
                {
                    string creatorDate2 = queryParam["F_CreatorDate2"].ToString();
                    extendLastFilterSql += $" AND t.ReturnVisitedCreatorTime <= '{ creatorDate2 }'";
                }

                if (!queryParam["returnState"].IsEmpty())
                {
                    var returnState = queryParam["returnState"].ToString();
                    if (returnState == "0")
                    {
                        extendLastFilterSql += " AND t.IsContainReturnVisitRecord = '0'";
                    }
                    else if (returnState == "1")
                    {
                        extendLastFilterSql += " AND t.IsContainReturnVisitRecord = '1'";
                    }
                }

                var sql=$@"SELECT  *
                        FROM(SELECT    sco.F_Id,
                                            sco.F_Id orderId,
                                            sco.F_DemandId,
                                            sco.F_WorkFormId,
                                            sco.F_FlowUserId,
                                            sco.F_OrderState,
                                            sco.F_OrderStateProcess,
                                            sco.F_CreatorTime,
                                            sco.F_LastModifyTime,
                                            sco.F_SignOut,
                                            scp.F_Source,
                                            scp.F_ActivityTheme,
                                            scp.F_ActivityType,
                                            scp.F_DemandCash,
                                            scp.F_ActivityStartDate,
                                            scp.F_ActivityEndDate,
                                            scp.F_ActivityCityId,
                                            scp.F_SiteType,
                                            scp.F_SiteArea,
                                            scp.F_Mating,
                                            scp.F_Intention,
                                            scp.F_Note,
                                            scp.F_State,
                                            atype.F_ActivityTypeName,
                                            su.F_RealName AS 'F_FlowUserName',
                                            scpc.F_Contact,
                                            sc.F_ClientName,
                                            (CASE WHEN rvr.F_Id IS NULL THEN 0
                                                   ELSE 1
                                              END) AS IsContainReturnVisitRecord,
                                            NULL AS ReturnVisitedCreatorTime,
                                            sccm.F_ContactId,
                                            scpc.F_ClientId
                                  FROM Site_Client_Order sco
                                       INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                                            LEFT JOIN(SELECT sid.F_ItemCode AS 'F_ActivityType' ,
                                                                sid.F_ItemName AS 'F_ActivityTypeName'
                                                        FROM Sys_Items si
                                                             INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
                                                                                      AND si.F_EnCode = 'ActivityType'
                                                      ) atype ON scp.F_ActivityType = atype.F_ActivityType
                                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                                            LEFT JOIN Site_Client_ReturnVisitRecord AS rvr ON rvr.F_OrderId = sco.F_Id
                                  WHERE sco.F_State = 1
                                            AND scp.F_State = 1
                                            AND ifnull(sco.F_IsCheck, 1) <> 0
                                            AND sco.F_OrderEnvironment = { environment } { F_GroupId } {extendFilterSql}
                                  UNION
                                  SELECT    sco.F_Id ,
                                            sco.F_Id orderId,
                                            sco.F_DemandId ,
                                            sco.F_WorkFormId ,
                                            sco.F_FlowUserId ,
                                            sco.F_OrderState ,
                                            sco.F_OrderStateProcess ,
                                            sco.F_CreatorTime ,
                                            sco.F_LastModifyTime ,
                                            sco.F_SignOut ,
                                            scp.F_Source ,
                                            scp.F_ActivityTheme ,
                                            scp.F_ActivityType ,
                                            scp.F_DemandCash ,
                                            scp.F_ActivityStartDate ,
                                            scp.F_ActivityEndDate ,
                                            scp.F_ActivityCityId ,
                                            scp.F_SiteType ,
                                            scp.F_SiteArea ,
                                            scp.F_Mating ,
                                            scp.F_Intention ,
                                            scp.F_Note ,
                                            scp.F_State ,
                                            atype.F_ActivityTypeName ,
                                            su.F_RealName AS 'F_FlowUserName' ,
                                            scpc.F_Contact ,
                                            sc.F_ClientName ,
                                            (CASE WHEN rvr.F_Id IS NULL THEN 0
                                                   ELSE 1
                                              END ) AS IsContainReturnVisitRecord,
                                            rvr.F_CreatorTime AS ReturnVisitedCreatorTime,
                                            sccm.F_ContactId,
                                            scpc.F_ClientId
                                  FROM Site_Client_ReturnVisitRecord AS rvr
                                            INNER JOIN Site_Client_Order sco ON sco.F_Id = rvr.F_OrderId
                                            INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                                            LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                                            LEFT JOIN(SELECT sid.F_ItemCode AS 'F_ActivityType' ,
                                                                sid.F_ItemName AS 'F_ActivityTypeName'
                                                        FROM Sys_Items si
                                                             INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
                                                                                      AND si.F_EnCode = 'ActivityType'
                                                      ) atype ON scp.F_ActivityType = atype.F_ActivityType
                                            LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                                            LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                                            LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                                    WHERE 1 = 1 { F_GroupId } {extendFilterSql}
                                ) AS t
                        WHERE 1 = 1 {extendLastFilterSql}
                        {orderSql}";

                var sqlCount = $@"SELECT  COUNT(*)
                                FROM    ( SELECT    sco.F_Id,
                                              (CASE WHEN rvr.F_Id IS NULL THEN 0
                                                   ELSE 1
                                              END) AS IsContainReturnVisitRecord,
                                              NULL AS ReturnVisitedCreatorTime
                                          FROM      Site_Client_Order sco
                                                    INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                                                    LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                                                    LEFT JOIN ( SELECT  sid.F_ItemCode AS 'F_ActivityType' ,
                                                                        sid.F_ItemName AS 'F_ActivityTypeName'
                                                                FROM    Sys_Items si
                                                                        INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
                                                                                              AND si.F_EnCode = 'ActivityType'
                                                              ) atype ON scp.F_ActivityType = atype.F_ActivityType
                                                    LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                                                    LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                                                    LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                                                    LEFT JOIN Site_Client_ReturnVisitRecord AS rvr ON rvr.F_OrderId = sco.F_Id
                                          WHERE sco.F_State = 1
                                                AND scp.F_State = 1
                                                AND ifnull(sco.F_IsCheck, 1) <> 0
                                                AND sco.F_OrderEnvironment = { environment } { F_GroupId } {extendFilterSql}
                                          UNION
                                          SELECT    sco.F_Id, 1, rvr.F_CreatorTime AS ReturnVisitedCreatorTime
                                          FROM      Site_Client_ReturnVisitRecord AS rvr
                                                    INNER JOIN Site_Client_Order sco ON sco.F_Id = rvr.F_OrderId
                                                    INNER JOIN Site_Clients_ProjectByDemand scp ON sco.F_DemandId = scp.F_Id
                                                    LEFT JOIN Sys_User su ON sco.F_FlowUserId = su.F_Id
                                                    LEFT JOIN ( SELECT  sid.F_ItemCode AS 'F_ActivityType' ,
                                                                        sid.F_ItemName AS 'F_ActivityTypeName'
                                                                FROM    Sys_Items si
                                                                        INNER JOIN Sys_ItemsDetail sid ON si.F_Id = sid.F_ItemId
                                                                                              AND si.F_EnCode = 'ActivityType'
                                                              ) atype ON scp.F_ActivityType = atype.F_ActivityType
                                                    LEFT JOIN Site_Clients_ContactMapping sccm ON sco.F_DemandId = sccm.F_DemandId
                                                    LEFT JOIN Site_Clients_ProjectByContact scpc ON sccm.F_ContactId = scpc.F_Id
                                                    LEFT JOIN Site_Clients sc ON scpc.F_ClientId = sc.F_Id
                                          WHERE 1 = 1 { F_GroupId } {extendFilterSql}
                                        ) AS t
                                     WHERE 1 = 1 {extendLastFilterSql};";

                var count = service.Count(sqlCount);
                pagination.records = count;

                var result = db.FindList<ClientOrderViewModel>(sql);
                return result;
            }
        }


        #endregion

        /// <summary>
        /// 提交回访记录
        /// </summary>
        /// <param name="entity"></param>
        public void SubmitReturnVisit(ClientReturnvisitrecordEntity entity)
        {
            var order = service.FindEntity(entity.F_OrderId);

            if (entity.F_State == 1)
            {
                order.F_OrderEnvironment = 2;
            }
            else
            {
                order.F_OrderEnvironment = 3;
                order.F_FlowUserId = "";

                var demand = demandOrderService.FindEntity(x => x.F_Id == order.F_DemandId);
                demand.F_State = 2;
                demandOrderService.Update(demand);
            }

            service.Update(order);
            clientReturnvisitrecordApp.SubmitForm(entity, "");
        }



        #region WeChat

        /// <summary>
        /// 根据订单号获取场地评论信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public SiteCommentDto GetWeChatSiteCommentDtoByOrderId(string orderId)
        {
            var sql = $@"SELECT c.F_SiteId AS siteId, c.F_SpaceId AS spaceId, s.title AS SiteTitle, s2.title AS SpaceTitle, p.F_Path AS pic
                        FROM Site_Client_OrderSignContract AS c
                        LEFT JOIN SL_Site AS s ON s.F_Id = c.F_SiteId
                        LEFT JOIN SL_Space AS s2 ON s2.F_Id = c.F_SpaceId
                        LEFT JOIN SL_Photos AS p ON p.photoable_id = c.F_SiteId AND p.photoable_type = 'Site'
                        WHERE p.is_cover = 1 AND F_OrderId = '{orderId}'
                        LIMIT 0, 1;";
            using (var db = new RepositoryBase())
            {
                var result = db.FirstOrDefault<SiteCommentDto>(sql);
                return result;
            }
        }
        #endregion
        #region 订单流程跳转
        /// <summary>
        /// 默认审核人都是admin
        /// </summary>
        private readonly string OrderFlowTake_CheckUserId = "EB03262C-AB60-4BC6-A4C0-96E66A4229FE";
        /// <summary>
        /// 订单流程跳转
        /// </summary>
        public void OrderFlowTake(string orderId, string Site_SpaceIds, string WorkFlowType, OrderPriceInput input)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                var Order = db.FindEntity<ClientOrderEntity>(orderId);
                if (Order.F_OrderState != 1)
                    return;
                switch (WorkFlowType)
                {
                    case "2":
                        TakeToRecommend(orderId, Site_SpaceIds, db); break;
                    case "3":
                        TakeToTakelook(orderId, Site_SpaceIds, db); break;
                    case "4":
                        TakeToReserve(orderId, Site_SpaceIds, db,input,4); break;
                    case "5":
                        TakeToReserve(orderId, Site_SpaceIds, db,input,5); break;
                    case "6":
                        TakeToImpress(orderId, Site_SpaceIds, db); break;
                }
            }

        }

        /// <summary>
        /// 跳转到带看场地
        /// </summary>
        public void TakeToRecommend(string orderId, string Site_SpaceIds, IRepositoryBase db)
        {
            var demandOrder = GetDemandOrderByOrderId(orderId);
            var randomNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (demandOrder != null)
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var orEntity = new ClientOrderrecommendEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_StartDate = demandOrder.F_ActivityStartDate,
                        F_EndDate = demandOrder.F_ActivityEndDate,
                        F_State = 1
                    };
                    orEntity.Create();
                    db.Insert<ClientOrderrecommendEntity>(orEntity);

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = 1;
                    mappingEntity.F_DetailId = orEntity.F_Id;
                    mappingEntity.F_State = 1;
                    mappingEntity.F_CheckUserId = OrderFlowTake_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                }
                var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                if (orderInfo != null)
                {
                    orderInfo.F_OrderStateProcess = -1;
                    orderInfo.F_OrderState = 2;
                    orderInfo.Modify(orderId);

                    db.Update<ClientOrderEntity>(orderInfo);
                }
                db.Commit();
            }
        }

        /// <summary>
        /// 跳转到意向场地
        /// </summary>
        public void TakeToTakelook(string orderId, string Site_SpaceIds, IRepositoryBase db)
        {
            var demandOrder = GetDemandOrderByOrderId(orderId);
            var randomNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (demandOrder != null)
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var entity = new ClientOrdertakelookEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_State = 1
                    };
                    entity.Create();
                    db.Insert<ClientOrdertakelookEntity>(entity);

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = 2;
                    mappingEntity.F_DetailId = entity.F_Id;
                    mappingEntity.F_State = 1;

                    mappingEntity.F_CheckUserId = OrderFlowTake_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                }

                var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                if (orderInfo != null)
                {
                    orderInfo.F_OrderStateProcess = -1;
                    orderInfo.F_OrderState = 3;
                    orderInfo.Modify(orderId);
                    db.Update<ClientOrderEntity>(orderInfo);
                }
                db.Commit();
            }
        }

        /// <summary>
        /// 跳转到价格审核
        /// </summary>
        public void TakeToIntention(string orderId, string Site_SpaceIds, IRepositoryBase db)
        {
            var demandOrder = GetDemandOrderByOrderId(orderId);
            var randomNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (demandOrder != null)
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var iEntity = new ClientOrderintentionEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_State = 1
                    };
                    iEntity.Create();
                    db.Insert<ClientOrderintentionEntity>(iEntity);

                    // 添加场地报价申请记录
                    var entity = new ClientOrderpricetalksEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_StartDate = demandOrder.F_ActivityStartDate,
                        F_EndDate = demandOrder.F_ActivityEndDate,
                        F_State = 1
                    };
                    entity.Create();
                    db.Insert<ClientOrderpricetalksEntity>(entity);


                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = 3;
                    mappingEntity.F_DetailId = iEntity.F_Id;
                    mappingEntity.F_State = 1;
                    mappingEntity.F_CheckUserId = OrderFlowTake_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                }
                var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                if (orderInfo != null)
                {
                    orderInfo.F_OrderStateProcess = -1;
                    orderInfo.F_OrderState = 4;
                    orderInfo.Modify(orderId);

                    db.Update<ClientOrderEntity>(orderInfo);
                }
                db.Commit();
            }
        }

        /// <summary>
        /// 跳转到场地预定
        /// </summary>
        public void TakeToReserve(string orderId, string Site_SpaceIds, IRepositoryBase db, OrderPriceInput input,int OrderState)
        {
            var demandOrder = GetDemandOrderByOrderId(orderId);
            var randomNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (demandOrder != null)
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var iEntity = new ClientOrderintentionEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_State = 1
                    };
                    iEntity.Create();
                    db.Insert<ClientOrderintentionEntity>(iEntity);

                    // 添加场地报价申请记录
                    var entity = new ClientOrderpricetalksEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_StartDate = demandOrder.F_ActivityStartDate,
                        F_EndDate = demandOrder.F_ActivityEndDate,
                        F_State = 1
                    };
                    entity.Create();
                    db.Insert<ClientOrderpricetalksEntity>(entity);

                    var Space = db.FindEntity<SpaceEntity>(spaceId);

                    var PriceInput = input.data.Where(t => t.F_SiteId == siteId && t.F_SpaceId == spaceId);
                    foreach (var it in PriceInput)
                    {
                        ClientOrderPriceDetailEntity detaiEntity = new ClientOrderPriceDetailEntity();
                        detaiEntity.Create();
                        detaiEntity.F_No = randomNo;
                        detaiEntity.F_OrderId = entity.F_OrderId;
                        detaiEntity.F_CheckId = "";
                        detaiEntity.F_ActivityName = demandOrder.F_ActivityTheme;
                        detaiEntity.F_ActivityCity = demandOrder.F_ActivityCityId;
                        detaiEntity.F_SiteId = siteId;
                        detaiEntity.F_SpaceId = spaceId;
                        detaiEntity.F_ActivityDate = demandOrder.F_ActivityStartDate.ToString();
                        detaiEntity.F_FeeType = it.F_FeeType;
                        detaiEntity.F_Unit = it.F_Unit;
                        detaiEntity.F_MarketPrice = it.F_MarketPrice;
                        detaiEntity.F_YunPrice = it.F_YunPrice;
                        detaiEntity.F_SalePrice = it.F_SalePrice;
                        detaiEntity.F_SpaceArea = it.F_SpaceArea;
                        detaiEntity.F_Quantity = it.F_Quantity;
                        detaiEntity.F_TotalPrice = it.F_Quantity * it.F_YunPrice;
                        db.Insert<ClientOrderPriceDetailEntity>(detaiEntity);
                    }
                   

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = OrderState-1;
                    mappingEntity.F_DetailId = iEntity.F_Id;
                    mappingEntity.F_State = 1;
                    mappingEntity.F_CheckUserId = OrderFlowTake_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                }
                var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                if (orderInfo != null)
                {
                    orderInfo.F_OrderStateProcess = -1;
                    orderInfo.F_OrderState = OrderState;
                    orderInfo.Modify(orderId);

                    db.Update<ClientOrderEntity>(orderInfo);
                }
                db.Commit();
            }
        }

        /// <summary>
        /// 跳转到用印申请
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="Site_SpaceIds"></param>
        public void TakeToImpress(string orderId, string Site_SpaceIds, IRepositoryBase db)
        {
            var demandOrder = GetDemandOrderByOrderId(orderId);
            var randomNo = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (demandOrder != null)
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var iEntity = new ClientOrderreserveEntity
                    {
                        F_No = randomNo,
                        F_OrderId = orderId,
                        F_SiteId = siteId,
                        F_SpaceId = spaceId,
                        F_StartDate = demandOrder.F_ActivityStartDate,
                        F_EndDate = demandOrder.F_ActivityEndDate,
                        F_State = 1,
                        F_ReserveTime = DateTime.Now
                    };
                    iEntity.Create();
                    db.Insert<ClientOrderreserveEntity>(iEntity);

                    SiteClientOrderMappingEntity mappingEntity = new SiteClientOrderMappingEntity();
                    mappingEntity.Create();
                    mappingEntity.F_ApplyType = 5;
                    mappingEntity.F_DetailId = iEntity.F_Id;
                    mappingEntity.F_State = 1;
                    mappingEntity.F_CheckUserId = OrderFlowTake_CheckUserId;
                    db.Insert<SiteClientOrderMappingEntity>(mappingEntity);
                }
                var orderInfo = db.FindEntity<ClientOrderEntity>(orderId);
                if (orderInfo != null)
                {
                    orderInfo.F_OrderStateProcess = -1;
                    orderInfo.F_OrderState = 6;
                    orderInfo.Modify(orderId);
                    db.Update<ClientOrderEntity>(orderInfo);
                }
                db.Commit();
            }
        }


        public List<OrderPriceCheckModel> GetCheckPrice(string Site_SpaceIds, string orderId)
        {
            List<OrderPriceCheckModel> result = new List<OrderPriceCheckModel>();
            var demandOrder = GetDemandOrderByOrderId(orderId);
            using (var db = new RepositoryBase())
            {
                var arr = Site_SpaceIds.Split(',');
                foreach (var item in arr)
                {
                    var siteId = item.Split('|')[0];
                    var spaceId = item.Split('|')[1];
                    var Site = db.FindEntity<SiteEntity>(siteId);
                    var Space = db.FindEntity<SpaceEntity>(spaceId);
                    var Pricecheck = new OrderPriceCheckModel()
                    {
                        F_SiteId = siteId,
                        SiteName = Site.title,
                        City = Site.city_id,
                        F_SpaceId = spaceId,
                        SpaceName = Space.title,
                        F_MarketPrice = Space.F_MarketPrice==null?"0": Space.F_MarketPrice.ToString(),
                        F_YunPrice = Space.F_YunPrice==null?"0": Space.F_YunPrice.ToString(),
                        F_SalePrice = Space.F_MarketPrice == null ? "0" : Space.F_MarketPrice.ToString(),
                        F_Units = Space.F_Units,
                        F_Area = Space.area==null?"": Space.area.ToString(),
                        F_StartDate = demandOrder.F_ActivityStartDate==null?"": demandOrder.F_ActivityStartDate.Value.ToString("yyyy-MM-dd"),
                        F_EndDate = demandOrder.F_ActivityEndDate==null?"": demandOrder.F_ActivityEndDate.Value.ToString("yyyy-MM-dd"),
                        F_ActivityTheme=demandOrder.F_ActivityTheme,
                        F_ActivityCityId=demandOrder.F_ActivityCityId,
                        F_Days = (demandOrder.F_ActivityEndDate - demandOrder.F_ActivityStartDate).Value.Days+1,
                    };
                    result.Add(Pricecheck);
                }
            }
            return result;
        }
        #endregion
    }
}

